Guest User

Untitled

a guest
Jan 20th, 2018
71
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.14 KB | None | 0 0
  1. template<typename Type>
  2. class BinaryTree {
  3. public:
  4. struct Node {
  5. Type data;
  6. Node* left{ nullptr };
  7. Node* right{ nullptr };
  8. Node(Type && value) : data{ std::move(value) } { }
  9. Node() = delete;
  10. };
  11. BinaryTree() noexcept { }
  12. BinaryTree(BinaryTree const &) = delete;
  13. BinaryTree(BinaryTree &&rhs) : root(rhs.root) { }
  14. BinaryTree& operator=(BinaryTree rhs) {
  15. using std::swap;
  16. swap(root, rhs.root);
  17. return *this;
  18. }
  19. ~BinaryTree() {
  20. reset();
  21. }
  22. // head, left leaf, right leaf
  23. // value type, tree will not be modified
  24. void preOrderTraversal(std::function<void(Type)> visit) {
  25. if( nullptr == root ) return;
  26. std::stack<Node*> stack;
  27. stack.push(root);
  28. while( !stack.empty() ) {
  29. auto node = stack.top();
  30. stack.pop();
  31. visit(node->data);
  32. if( node->right ) {
  33. stack.push(node->right);
  34. }
  35. if( node->left ) {
  36. stack.push(node->left);
  37. }
  38. }
  39. }
  40. // reference type, tree will be modified; so the tree need update order of nodes.
  41. void preOrderTraversal(std::function<void(Type&)> visit) {
  42. if( nullptr == root ) return;
  43. std::stack<Node*> stack;
  44. stack.push(root);
  45. while( !stack.empty() ) {
  46. auto node = stack.top();
  47. stack.pop();
  48. visit(node->data);
  49. if( node->right ) {
  50. stack.push(node->right);
  51. }
  52. if( node->left ) {
  53. stack.push(node->left);
  54. }
  55. }
  56. update(); // some update function keep the tree in binary search tree order.
  57. }
  58. private:
  59. Node* root{nullptr};
  60. }
  61.  
  62. // just as an example, readonly can not change the tree,
  63. // while write may change the tree
  64. void readonly(double value) {
  65. std::cout <<value++ << std::endl;
  66. }
  67.  
  68. void write(Type & value) {
  69. std::cout <<value++ << std::endl;
  70. }
  71.  
  72. int main() {
  73. BinaryTree<double> btree;
  74.  
  75. // ... working on the tree..., push, pop, etc.
  76.  
  77. btree.preOrderTraversal(readonly);
  78. btree.preOrderTraversal(write);
  79. }
Add Comment
Please, Sign In to add comment