sashomaga

Binary tree

Feb 24th, 2014
126
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 2.01 KB | None | 0 0
  1. struct node{
  2.     int key_value;
  3.     node* left;
  4.     node* right;
  5. };
  6.  
  7. class btree
  8. {
  9.     public:
  10.         btree();
  11.         ~btree();
  12.  
  13.         void insert(int key);
  14.         node *search(int key);
  15.         void destroy_tree();
  16.  
  17.     private:
  18.         void destroy_tree(node *leaf);
  19.         void insert(int key, node *leaf);
  20.         node *search(int key, node *leaf);
  21.        
  22.         node *root;
  23. };
  24.  
  25. btree::btree()
  26. {
  27.   root=NULL;
  28. }
  29.  
  30. btree::~btree()
  31. {
  32.   destroy_tree();
  33. }
  34.  
  35. void btree::destroy_tree(node *leaf)
  36. {
  37.   if(leaf!=NULL)
  38.   {
  39.     destroy_tree(leaf->left);
  40.     destroy_tree(leaf->right);
  41.     delete leaf;
  42.   }
  43. }
  44.  
  45. void btree::insert(int key, node *leaf)
  46. {
  47.   if(key< leaf->key_value)
  48.   {
  49.     if(leaf->left!=NULL)
  50.     {
  51.         insert(key, leaf->left);
  52.     }
  53.     else
  54.     {
  55.         leaf->left=new node;
  56.         leaf->left->key_value=key;
  57.         leaf->left->left=NULL;    //Sets the left child of the child node to null
  58.         leaf->left->right=NULL;   //Sets the right child of the child node to null
  59.     }  
  60.   }
  61.   else if(key>=leaf->key_value)
  62.   {
  63.     if(leaf->right!=NULL)
  64.     {
  65.       insert(key, leaf->right);
  66.     }
  67.     else
  68.     {
  69.       leaf->right=new node;
  70.       leaf->right->key_value=key;
  71.       leaf->right->left=NULL;  //Sets the left child of the child node to null
  72.       leaf->right->right=NULL; //Sets the right child of the child node to null
  73.     }
  74.   }
  75. }
  76.  
  77. node *btree::search(int key, node *leaf)
  78. {
  79.   if(leaf!=NULL)
  80.   {
  81.     if(key==leaf->key_value)
  82.     {
  83.       return leaf;
  84.     }
  85.     if(key<leaf->key_value)
  86.     {
  87.       return search(key, leaf->left);
  88.     }
  89.     else
  90.     {
  91.       return search(key, leaf->right);
  92.     }
  93.   }
  94.   else return NULL;
  95. }
  96.  
  97. //PUBLIC
  98. //public if no root
  99. void btree::insert(int key)
  100. {
  101.   if(root!=NULL)
  102.     insert(key, root);
  103.   else
  104.   {
  105.     root=new node;
  106.     root->key_value=key;
  107.     root->left=NULL;
  108.     root->right=NULL;
  109.   }
  110. }
  111.  
  112. node *btree::search(int key)
  113. {
  114.   return search(key, root);
  115. }
  116.  
  117. void btree::destroy_tree()
  118. {
  119.   destroy_tree(root);
  120. }
Advertisement
Add Comment
Please, Sign In to add comment