fork download
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3.  
  4. //data struct for BST node
  5. typedef struct BST
  6. {
  7. int data;
  8. struct BST *left;
  9. struct BST *right;
  10. }node;
  11.  
  12. //make node from given data
  13. node* makeNode(int data)
  14. {
  15. node *n=(node*)malloc(sizeof(node));
  16. n->data=data;
  17. n->left=NULL;
  18. n->right=NULL;
  19.  
  20. return n;
  21. }
  22.  
  23. //insert node in BST
  24. node* insert(node* root,int key)
  25. {
  26. if(root==NULL)
  27. return makeNode(key);
  28.  
  29. if(key < root->data)
  30. root->left=insert(root->left,key);
  31. else
  32. root->right=insert(root->right,key);
  33.  
  34. return root;
  35. }
  36.  
  37. //inorder printing prints in sorted order
  38. void inorder(node* root)
  39. {
  40. if(root==NULL)
  41. return;
  42.  
  43. inorder(root->left);
  44. printf("%d ",root->data);
  45. inorder(root->right);
  46. }
  47.  
  48. //preorder printing
  49. void preorder(node* root)
  50. {
  51. if(root==NULL)
  52. return;
  53. printf("%d ",root->data);
  54. preorder(root->left);
  55. preorder(root->right);
  56. }
  57.  
  58. //postorder printing
  59. void postorder(node* root)
  60. {
  61. if(root==NULL)
  62. return;
  63. postorder(root->left);
  64. postorder(root->right);
  65. printf("%d ",root->data);
  66. }
  67.  
  68. //search key in tree
  69. node *search(node *root, int key)
  70. {
  71. node *t=NULL;
  72.  
  73. if(root==NULL) //check if tree is empty
  74. t = NULL;
  75. else if(root->data==key) //key exists at current node
  76. t = root;
  77. else if(key < root->data) //key in left subtree
  78. t = search(root->left,key);
  79. else
  80. t = search(root->right,key); //key in right subtree
  81.  
  82. return t;
  83. }
  84.  
  85. //driver function
  86. int main(void) {
  87. // your code goes here
  88. node *root=NULL;
  89. int s,i,key;
  90. scanf("%d",&s);
  91. //while(s--)
  92. for(i=0;i<s;i++)
  93. {
  94. scanf("%d",&key);
  95. root=insert(root,key);
  96. }
  97. node* result=search(root,1);
  98. if(result==NULL)
  99. printf("Not found\n");
  100. else printf("Found\n");
  101. return 0;
  102. }
  103.  
Success #stdin #stdout 0s 2384KB
stdin
5
5 4 3 2 1
stdout
Found