The property of BST (left < root < right) allows us to eliminate half of the tree in each recursive step.
- Base case: If
rootis None orroot.val == val, returnroot. - If
val < root.val:- Search in the left subtree:
return searchBST(root.left, val).
- Search in the left subtree:
- Else:
- Search in the right subtree:
return searchBST(root.right, val).
- Search in the right subtree:
- Time Complexity: O(H) where H is tree height.
- Space Complexity: O(H).
def search_bst(root, val):
if not root or root.val == val:
return root
if val < root.val:
return search_bst(root.left, val)
else:
return search_bst(root.right, val)