Given the root of a balanced BST root
, and a target value target
, return whether the tree contains the target value.
Example:
Explanation: The tree contains a node with the target value 3, so we return True.
The solution is just to apply Binary Search to the BST. Whenever target
is smaller than the current value, we go left. And whenever target
is larger than the current value, we go right. For example, searching for the number 3 looks like this:
0. Problem
1. Recursion
2. Base case
If we get to a node that's None, then we know the target is not in that tree.
3. Code
Time Complexity O(logn)
Space Complexity O(logn) for the Call Stack.
You can easily make this iterative:
Time Complexity O(logn)
Space Complexity O(1)