Sponsored
Sponsored
This approach uses the recursive traversal of the BST properties. It checks if the current node's value is equal to the target value. If it is, it returns the subtree rooted at the current node. If the target value is less than the current node, it recurses into the left subtree; if greater, it recurses into the right subtree. This method leverages the BST's inherent properties to narrow down the search.
Time Complexity: O(h) where h is the height of the tree, as we traverse from the root to a leaf.
Space Complexity: O(h) due to the recursion stack.
1class TreeNode {
2 int val;
3 TreeNode left;
4 TreeNode right;
5 TreeNode() {}
6 TreeNode(int val) { this.val = val; }
7 TreeNode(int val, TreeNode left, TreeNode right) {
8 this.val = val;
9 this.left = left;
10 this.right = right;
11 }
12}
13
14class Solution {
15 public TreeNode searchBST(TreeNode root, int val) {
16 if (root == null || root.val == val) {
17 return root;
18 }
19 if (val < root.val) {
20 return searchBST(root.left, val);
21 }
22 return searchBST(root.right, val);
23 }
24}
In Java, this recursive solution searches for the node in the BST with the given value. It checks if the root is null
or its value matches the target, else it calls itself on the left or right child based on the comparison.
In this approach, we use an iterative solution instead of recursion to save stack space. Starting from the root, we use a loop to traverse the tree. At each node, we check if it matches the target value. If it matches, we return the node; if not, we decide to move to the left or right child based on the BST property. The absence of a matching node returns null
.
Time Complexity: O(h) where h is tree height.
Space Complexity: O(1) since we're only using a few extra pointers.
1
The iterative version in Java uses a while
loop to traverse the BST, allowing it to navigate easily to the node holding the desired value, otherwise it returns null
.