Given the root of a BST and a target value, find the node with the corresponding value.
I: Given the root 4, target value is 2
4
/ \
2 7
/ \
1 3
O:
2
/ \
1 3
Searching a balanced BST is fast. O(logn) time.
def searchBST(self, root: TreeNode, val: int) -> TreeNode:
if root is None:
return None
if root.val == val:
return root
if val >= root.val:
return self.searchBST(root.right, val)
else:
return self.searchBST(root.left, val)