fork download
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <stdbool.h>
  4. typedef struct BSTnode {
  5. int data;
  6. struct BSTnode *left;
  7. struct BSTnode *right;
  8. } BSTnode;
  9.  
  10. BSTnode *getNewNode(int data){
  11. BSTnode *newNode = (BSTnode*)malloc(sizeof(BSTnode));
  12. newNode->data=data;
  13. newNode->left=newNode->right=NULL;
  14. return newNode;
  15. }
  16. BSTnode* InsertNew(BSTnode *root,int data){
  17. if(root == NULL){
  18. root = getNewNode(data);
  19. }
  20. else if(data <= root->data){
  21. root->left = InsertNew(root->left,data);
  22. } else{
  23. root->right = InsertNew(root->right,data);
  24. }
  25. return root;
  26. }
  27.  
  28. bool search(BSTnode *root, int data){
  29. if(root== NULL) return false;
  30. else if(root->data == data) return true;
  31. else if (data < root->data) return search(root->left,data);
  32. else return search(root->right,data);
  33.  
  34. }
  35. int main()
  36. {
  37. //node to store root
  38.  
  39. BSTnode *root = NULL;
  40.  
  41. root = InsertNew(root,34);
  42. root = InsertNew(root,4);
  43. root = InsertNew(root,3);
  44. root = InsertNew(root,1);
  45.  
  46. int num;
  47. printf("enter a number : \n");
  48. scanf("%d", &num);
  49.  
  50. if(search(root,num)==true){
  51. printf("found");
  52. }else{
  53. printf("not found");
  54. }
  55. return 0;
  56. }
Success #stdin #stdout 0s 9424KB
stdin
12
stdout
enter a number : 
not found