SDE & MLE Prep

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