Advertisement
apl-mhd

BinarySearchTree

Apr 21st, 2017
124
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.40 KB | None | 0 0
  1. #include <iostream>
  2. #include <cstdio>
  3. using namespace std;
  4.  
  5. struct tree{
  6. int data;
  7. struct tree *left;
  8. struct tree *right;
  9. };
  10.  
  11. typedef struct tree tree;
  12.  
  13. tree *getNode(tree *root, int x){
  14.  
  15. root=new tree();
  16. root->data =x;
  17. root->left = NULL;
  18. root->right = NULL;
  19. return root;
  20. }
  21. tree *insert(tree *root,int data){
  22.  
  23. if(root == NULL){
  24.  
  25. root = new tree();
  26. root = getNode(root, data);
  27.  
  28. }
  29.  
  30. else if(data<=root->data){
  31.  
  32. root->left = insert(root->left,data);
  33.  
  34. }
  35. else{
  36. root->right = insert(root->right,data);
  37. }
  38.  
  39. return root;
  40. }
  41.  
  42. int minimum(tree *root){
  43.  
  44. if(root->left!=NULL)
  45. return minimum(root->left);
  46.  
  47. else
  48.  
  49. return root->data;
  50. }
  51.  
  52.  
  53. bool search(tree *root, int item){
  54.  
  55. if(root == NULL)
  56. return false;
  57. else if(root->data == item)
  58. return true;
  59. else if(item <= root->data)
  60. return search(root->left,item);
  61. else
  62. return search(root->right,item);
  63.  
  64. }
  65.  
  66. int main(int argc, char **argv)
  67. {
  68. tree *root=NULL;
  69.  
  70. root = insert(root, 10);
  71. root = insert(root, 5);
  72. root = insert(root, 20);
  73. root = insert(root, 40);
  74. root = insert(root,-1);
  75.  
  76.  
  77.  
  78. //cout<<minimum(root);
  79. //cout<<search(root,10)<<endl;
  80. // cout<<search(root,100)<<endl;
  81. cout<<search(root,40)<<endl;
  82. //cout<<root->data<<endl;
  83. //cout<<root->left->left->data<<endl;
  84. //cout<<root->right->right->data<<endl;
  85.  
  86. return 0;
  87. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement