fork download
  1. #include <stdio.h>
  2. #include <malloc.h>
  3.  
  4. struct Node {
  5. int data;
  6. struct Node *left;
  7. struct Node *right;
  8. };
  9.  
  10. struct Node* insert(struct Node *root, int data) {
  11.  
  12. if(root == NULL) {
  13. root = (struct Node*)malloc(sizeof(struct Node));
  14. root->data = data;
  15. root->left = NULL;
  16. root->right = NULL;
  17. } else {
  18. if(root->data > data) {
  19. root->left = insert(root->left, data);
  20. } else if(root->data < data) {
  21. root->right = insert(root->right, data);
  22. }
  23. }
  24. return root;
  25. }
  26.  
  27. int search(struct Node *root, int key) {
  28.  
  29. if(root != NULL) {
  30.  
  31. if(root->data == key) {
  32. return 1;
  33. } else if(root->data > key) {
  34. return search(root->left, key);
  35. } else {
  36. return search(root->right, key);
  37. }
  38.  
  39. }
  40. return 0;
  41. }
  42.  
  43. void inorder(struct Node*root) {
  44. if(root != NULL) {
  45. inorder(root->left);
  46. printf("%d ", root->data);
  47. inorder(root->right);
  48. }
  49. }
  50. int main(int argc, char const *argv[]) {
  51.  
  52. struct Node *root = NULL;
  53. root = insert(root, 101);
  54. for(int i = 10; i >= 0; i--)
  55. insert(root, i) ;
  56. inorder(root) ;
  57. int keysearch = 1011;
  58. printf("%d", search(root, keysearch));
  59. return 0;
  60. }
  61.  
Success #stdin #stdout 0s 5528KB
stdin
Standard input is empty
stdout
0 1 2 3 4 5 6 7 8 9 10 101 0