fork(8) download
  1. #include<stdio.h>
  2. #include<malloc.h>
  3.  
  4. struct binaryTreeNode{
  5. int data;
  6. struct binaryTreeNode * left;
  7. struct binaryTreeNode * right;
  8. };
  9.  
  10. int findElementInTreeRecursive(struct binaryTreeNode * root, int num)
  11. {
  12. // A variable for root value
  13. int root_val;
  14.  
  15. // Variable to store values in left and right tree
  16. int left, right;
  17.  
  18. if(root != NULL)
  19. {
  20. // Get the root value
  21. root_val = root -> data;
  22.  
  23. if(root_val == num)
  24. return 1;
  25.  
  26. // Find the element in left sub-tree
  27. // If found, we return 1
  28. left = findElementInTreeRecursive(root -> left, num);
  29. if(left == 1)
  30. return 1;
  31. else
  32. {
  33. // We need to find the element in right sub-tree
  34. right = findElementInTreeRecursive(root -> right, num);
  35. if(right == 1)
  36. return 1;
  37. }
  38. }
  39.  
  40. // If we reach here, that means the element was not found
  41. return 0;
  42. }
  43.  
  44. // Test the above functions
  45. int main(void)
  46. {
  47. // Initialize the tree
  48. struct binaryTreeNode * root = (struct binaryTreeNode *)malloc(sizeof(struct binaryTreeNode));
  49. root-> data = 1;
  50. struct binaryTreeNode * l = (struct binaryTreeNode *)malloc(sizeof(struct binaryTreeNode));
  51. l -> data = 2;
  52. struct binaryTreeNode * ll = (struct binaryTreeNode *)malloc(sizeof(struct binaryTreeNode));
  53. ll -> data = 4;
  54. ll -> left = ll -> right = NULL;
  55. struct binaryTreeNode * lr = (struct binaryTreeNode *)malloc(sizeof(struct binaryTreeNode));
  56. lr -> data = 5;
  57. lr -> left = lr -> right = NULL;
  58. l -> left = ll;
  59. l -> right = lr;
  60. struct binaryTreeNode * r = (struct binaryTreeNode *)malloc(sizeof(struct binaryTreeNode));
  61. r -> data = 3;
  62. struct binaryTreeNode * rl = (struct binaryTreeNode *)malloc(sizeof(struct binaryTreeNode));
  63. rl -> data = 6;
  64. rl -> left = rl -> right = NULL;
  65. struct binaryTreeNode * rr = (struct binaryTreeNode *)malloc(sizeof(struct binaryTreeNode));
  66. rr -> data = 7;
  67. rr -> left = rr -> right = NULL;
  68. r -> left = rl;
  69. r -> right = rr;
  70. root -> left = l;
  71. root -> right = r;
  72.  
  73. // recursive version
  74. if(findElementInTreeRecursive(root, 90))
  75. printf("PRESENT");
  76. else
  77. printf("NOT PRESENT");
  78.  
  79. return 0;
  80. }
Success #stdin #stdout 0s 2380KB
stdin
Standard input is empty
stdout
NOT PRESENT