700. Search in a Binary Search Tree
Problem
Find the node with value val in a BST and return the subtree rooted there, or null if it doesn't exist.
Example: [4,2,7,1,3], val = 2 → [2,1,3]
Walk down from the root: go left if the target is smaller, right if larger. No recursion needed.
Complexity: O(h).
class Solution:
def searchBST(self, root: Optional[TreeNode], val: int) -> Optional[TreeNode]:
while root and root.val != val:
root = root.left if val < root.val else root.right
return root
assert tree_vals(Solution().searchBST(make_tree([4, 2, 7, 1, 3]), 2)) == [2, 1, 3]
assert Solution().searchBST(make_tree([4, 2, 7, 1, 3]), 5) is None
assert tree_vals(Solution().searchBST(make_tree([4, 2, 7, 1, 3]), 7)) == [7]
class Solution {
public TreeNode searchBST(TreeNode root, int val) {
while (root != null && root.val != val) root = val < root.val ? root.left : root.right;
return root;
}
}
func searchBST(root *TreeNode, val int) *TreeNode {
for root != nil && root.Val != val {
if val < root.Val {
root = root.Left
} else {
root = root.Right
}
}
return root
}