From db011cc091353f9966b78f0ed1e73a8e4a68f7fa Mon Sep 17 00:00:00 2001 From: Akhil Soni <58397226+akhil-maker@users.noreply.github.com> Date: Mon, 2 Oct 2023 14:57:29 +0530 Subject: [PATCH] Create searchInBST.c --- algorithms/searchInBST.c | 67 ++++++++++++++++++++++++++++++++++++++++ 1 file changed, 67 insertions(+) create mode 100644 algorithms/searchInBST.c diff --git a/algorithms/searchInBST.c b/algorithms/searchInBST.c new file mode 100644 index 00000000..ed219d0c --- /dev/null +++ b/algorithms/searchInBST.c @@ -0,0 +1,67 @@ +#include +#include +struct Node +{ + int data; + struct Node *left; + struct Node *right; +}; +struct Node *createNode(int data) +{ + struct Node *n = malloc(sizeof(struct Node)); + n->data = data; + n->left = NULL; + n->right = NULL; + return n; +} +struct Node *Recsearch(struct Node *root, int key) +{ + if (root == NULL) + { + return NULL; + } + if (key == root->data) + { + return root; + } + else if (key < root->data) + { + return Recsearch(root->left, key); + } + else + { + return Recsearch(root->right, key); + } +} +struct Node *Itersearch(struct Node *root, int key) +{ + while (root!=NULL){ + if (key==root->data){ + return root; + } + else if (keydata){ + root = root->left; + } + else{ + root = root->right; + } + } + return NULL; +} +int main() +{ + struct Node *p = createNode(50); + struct Node *q = createNode(40); + struct Node *r = createNode(20); + struct Node *s = createNode(45); + struct Node *t = createNode(60); + p->left = q; + q->left = r; + q->right = s; + p->right = t; + struct Node *n = Recsearch(p, 45); + printf("Search node: %d\n", n->data); + struct Node *m = Itersearch(p, 20); + printf("Search node: %d", m->data); + return 0; +}