Member-only story
Search In a Binary Search Tree 🌳| Daily LeetCode Challenge | Day 14 | Coding Interview
2 min readApr 14, 2022
This is the 14th problem of the challenge and it's just a simple BST traversal.
Description
We are given a BST and an integer, we have to find the value in the BST and return the root of the subtree holding the node with the passed value. Return null if the passed value does not exist.
Example 1:
Input: root = [4,2,7,1,3], val = 2
Output: [2,1,3]Example 2:
Input: root = [4,2,7,1,3], val = 5
Output: []
Solution for the search in BST
We are given the root of the tree, first, we will find the node in the left subtree and then in the right subtree, and finally, look at the current node if it holds the value equal to our passed parameter.
The algorithm for searching
- Check if the root is null, if it is then return null, showing the value does not exist.
- Call the function recursively on the left…