Problem Statement: Given the root of a binary search tree and an integer value say x. We have to find the node in the BST such that the node's value is equal to x. If it exits in BST then return true, otherwise false.
A binary tree is considered as BST if it satisfies below conditions:
- The left subtree of a node contains only nodes with values less than the node's value.
- The right subtree of a node contains only nodes with values greater than the node's value.
- Both the left and right subtrees must also be binary search trees.
Example 1:
Output: true
Example 2:
Output: false
Approach:
The approach is simple we will take benefit from the property of BST. We have seen that left subtree of a node contains only nodes with values less than the node's value and right subtree of a node contains only nodes with values greater than the node's value. Hence we will start from root if x is smaller than current node's value we will go to left subtree else if the x is greater than current node's value we will try searching x in right subtree if both of these conditions is not excecuted that means we have found a node whose value is equal to x and return true.
If we got root equal to null means we haven't found any node with value equal to x. Hence, return false.
Code Implementation:
Output:
true
Complexity Analysis:
Time Complexity: O(h), where h is the height of binary tree.
Space Complexity: O(n), Considering the stack space where n is number of nodes visited.
If you want to contribute such articles to solutions2coding.com please click here. Thank you!
very nice explanation
ReplyDelete