Search in a BST
Return the subtree rooted at the node whose value equals val, or null.
Intuition
The BST property is a built-in compass: smaller values live left, larger right. Compare at each node and walk one side — it's binary search wearing a tree costume.
A BST turns searching into deciding: at every node one comparison eliminates an entire subtree. Whenever the structure tells you which way to go rather than forcing you to try both, the traversal is a walk, not a search — so it's O(h) and needs no stack, no queue, no recursion.
Approach
Three-way compare
val == node → done. val < node → go left. val > node → go right.
Iterate, don't recurse
A while loop avoids stack frames — the path is a straight walk.
Cost is the height
Balanced BST → O(log n); degenerate chain → O(n).
Solution & live demo
Common pitfalls
Searching both subtrees like a plain binary tree
if not root or root.val == val: return root return self.searchBST(root.left, val) or self.searchBST(root.right, val)
while root and root.val != val:
root = root.left if val < root.val else root.right
return rootThis returns the right node but visits every node, making it O(n) and throwing away the only thing a BST gives you. The ordering means a smaller target cannot possibly be on the right, so half the tree is ruled out at each step without looking at it.
Returning None instead of the subtree on a miss
while root:
if root.val == val: return root
root = root.left if val < root.val else root.right
return Nonewhile root and root.val != val:
root = root.left if val < root.val else root.right
return rootBoth are correct here, but the problem asks for the subtree rooted at the match, and the loop-condition form returns exactly that in one exit — the loop stops either on the match or on None, which is already the required answer.
Edge cases
Walk falls off a null child → return None.
Loop exits immediately.