Problem Description
Given the root of a binary search tree (BST) and an integer value, find the node in the BST with the given value. If such a node exists, return the subtree rooted at that node; otherwise, return null.
Key Insights
- Utilize the BST property: for any node, all values in the left subtree are smaller and all values in the right subtree are larger.
- This property allows efficient searching by choosing the correct subtree to continue the search.
- The problem can be recursively or iteratively solved.
- Recursion typically leads to a cleaner, more intuitive implementation.
Space and Time Complexity
Time Complexity: O(h), where h is the height of the tree.
Space Complexity: O(h) due to recursion stack in the recursive approach, or O(1) if an iterative approach is used.
Solution
We traverse the BST starting at the root. For each node, we compare the target value with the current node's value:
- If the values match, we return the current node.
- If the target value is less, we recursively (or iteratively) search the left subtree.
- If the target value is greater, we proceed to search the right subtree. By making use of the BST properties, we avoid checking every node, which makes the approach efficient.
Code Solutions
Python:
JavaScript:
C++:
Java: