37: Implement a binary search tree (BST).
⏳⌚ 00:00:00

Question:-

Implement a binary search tree (BST).
Example 1:
Input:
The BST is created by inserting several elements (50, 30, 20, 40, 70, 60, 80) into it.
Two keys are selected for searching: 6 and 60.
Output:
6 not found
60 found

Steps to solve:-

1. struct node:-
Defines a structure for a binary tree node, containing a key (integer value), a pointer to the left child, and a pointer to the right child.
2. newNode(int item):-
A utility function to create a new BST node with the specified key value. It allocates memory for the node, initializes its key value, and sets both child pointers to NULL.
3. insert(struct node* node, int key):-
A recursive utility function to insert a new node with the given key into the BST. It follows the principles of a BST to decide whether to insert the key in the left or right subtree based on a comparison with the current node's key.
4. search(struct node* root, int key):-
A recursive utility function to search for a key in the BST. It recursively traverses the BST, comparing the target key with the keys of nodes to determine if the key is present in the tree.
5. In the main function:-
A struct node* root pointer is initialized as NULL, representing an empty BST. Several elements are inserted into the BST using the insert function. Two keys, 6 and 60, are used to demonstrate searching in the BST. The search function is called for each key to check if they are found or not, and appropriate messages are printed.

solution->

View Code 1
Time Complexity = O(h)
Space Complexity = O(h)
h = height