Given a BST, write an efficient function to search a given key in it. The algorithm should return the parent node of the key and print if the key is the left or right node of the parent node. If the key is not present in the BST, the algorithm should be able to determine that.

Searching a binary search tree for a specific key can be programmed recursively or iteratively.

 
Search key in the BST

Practice this problem

We begin by examining the root node. If the tree is null, the key we are searching for does not exist in the tree. Otherwise, if the key equals that of the root, the search is successful, we return the node. If the key is less than that of the root, we search the left subtree. Similarly, if the key is greater than that of the root, we search the right subtree. This process is repeated until the key is found or the remaining subtree is null. If the searched key is not found after a null subtree is reached, then the key is not present in the tree.

This can be easily expressed as a recursive algorithm. The implementation can be seen below in C++, Java, and Python:

C++


Download  Run Code

Output:

The given key is the right node of the node with key 20

Java


Download  Run Code

Output:

The given key is the right node of the node with key 20

Python


Download  Run Code

Output:

The given key is the right node of the node with key 20

This algorithm searches from the tree’s root to the leaf farthest from the root in the worst-case. The search operation takes time proportional to the tree’s height. On average, binary search trees with n nodes have O(log(n)) height. However, in the worst case, binary search trees can have O(n) height (for skewed trees where all the nodes except the leaf have one and only one child) when the unbalanced tree resembles a linked list.

The space used by the call stack is also proportional to the tree’s height. The algorithm can be implemented iteratively to avoid use of extra space.

C++


Download  Run Code

Output:

The given key is the right node of the node with key 20

Java


Download  Run Code

Output:

The given key is the right node of the node with key 20

Python


Download  Run Code

Output:

The given key is the right node of the node with key 20

 
Also See:

Insertion in a BST – Iterative and Recursive Solution

Deletion from BST (Binary Search Tree)

 
References: https://en.wikipedia.org/wiki/Binary_search_tree