700. Search in a Binary Search Tree
Given the root node of a binary search tree (BST) and a value. You need to find the node in the BST that the node's value equals the given value. Return the subtree rooted with that node. If such node doesn't exist, you should return NULL.
For example,
You should return this subtree:
In the example above, if we want to search the value 5
, since there is no node with value 5
, we should return NULL
.
Note that an empty tree is represented by NULL
, therefore you would see the expected output (serialized tree format) as []
, not null
.
Recursive:
Iterative:
Let's discuss the time complexity and space complexity of the search operation in a BST whose height is h
. Focus on the recursion solution first. In the worse case, the depth of our recursion is equal to the height of the tree. Therefore, the time complexity of the recursion solution is O(h)
. And taking system stack into consideration, the space complexity should be O(h)
in the worst case as well.
What about the iterative solution? The time complexity will be equal to the loop time which is also O(h)
while the space complexity is O(1)
since we do not need system stack anymore in an iterative solution.
Question:
If you do not know the height of the BST
h
but you are given the total number of nodesN
of the BST, can you express the time complexity and space complexity usingN
instead ofh
?
Hint:
What's the difference of the relationship between
N
andh
in the best case and the relationship in the worst case?
The time complexity is O(h)
. Or O(N)
in the worst case and O(logN)
ideally if the tree is well organized.
The space complexity is O(h)
. In other word, O(N)
in the worst case and O(logN)
ideally. If you implement the algorithm iteratively, the space complexity can be O(1)
.
Last updated