Advertisement
Guest User

with struct

a guest
Feb 7th, 2016
50
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.18 KB | None | 0 0
  1.  
  2. //Binary search tree
  3. #include<bits/stdc++.h>
  4. using namespace std;
  5. struct BstNode{
  6. int data;
  7. BstNode* left;
  8. BstNode* right;
  9. };
  10.  
  11. BstNode* GetNewNode(int data)
  12. {
  13. BstNode* NewNode= new BstNode();
  14. NewNode->data=data;
  15. NewNode->left=NewNode->right=NULL;
  16. return NewNode;
  17. }
  18. BstNode* insert(BstNode* root, int data)
  19. {
  20. if(root==NULL)
  21. root=GetNewNode(data);
  22. else if(data<=root->data)
  23. root->left=insert(root->left, data);
  24. else if(data>root->data)
  25. root->right=insert(root->right, data);
  26. return root;
  27. }
  28. bool search(BstNode* root, int data)
  29. {
  30. if(root==NULL)
  31. return false;
  32. else if(root->data==data)
  33. return true;
  34. else if(data<=root->data)
  35. return search(root->left, data);
  36. else
  37. return search(root->right, data);
  38. }
  39.  
  40. int main()
  41. {
  42. BstNode* root=NULL;
  43. root=insert(root, 50);
  44. root=insert(root, 90);
  45. root=insert(root, 7);
  46. root=insert(root, -5);
  47. if(search(root, -5))
  48. cout<<"-5 is found in the binary search tree"<<'\n';
  49. if(!search(root, 8))
  50. cout<<"8 isn't found in the binary search tree";
  51. return 0;
  52. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement