Problem
Note: Your solution should have only one BST traversal and O(1)
extra space complexity, since this is what you will be asked to accomplish in an interview.
A tree is considered a binary search tree (BST) if for each of its nodes the following is true:
- The left subtree of a node contains only nodes with keys less than the node’s key.
- The right subtree of a node contains only nodes with keys greater than the node’s key.
- Both the left and the right subtrees must also be binary search trees.
Given a binary search tree t
, find the smallest element in it.
Note that smallest element means element in increasing order. See examples for better understanding.
Example
For
t = { "value": 3, "left": { "value": 1, "left": null, "right": null }, "right": { "value": 5, "left": { "value": 4, "left": null, "right": null }, "right": { "value": 6, "left": null, "right": null } } }
and
k = 4
, the output should besolution(t, k) = 5
.Here is what
t
looks like:3 / \ 1 5 / \ 4 6
The values of
t
are[1, 3, 4, 5, 6]
, and the smallest is5
.For
t = { "value": 1, "left": { "value": -1, "left": { "value": -2, "left": null, "right": null }, "right": { "value": 0, "left": null, "right": null } }, "right": null }
and
k = 1
, the output should besolution(t, k) = -2
.Here is what
t
looks like:1 / -1 / \ -2 0
The values of
t
are[-2, -1, 0, 1]
, and the smallest is-2
.
Solution
DFS or BFS? BFS starts visiting nodes from root while DFS starts visiting nodes from leaves. So if our problem is to search something that is more likely to closer to root, we would prefer BFS. And if the target node is close to a leaf, we would prefer DFS.
We can use inOrder traversal because the goals is finding value from sorted data.
<CH.Section>
- Create an empty slice as
stack
- Initialize current node as root
- If current is NULL and stack is not empty then
- If current is NULL and stack is empty then we are done.
func solution(t *Tree, k int) int {
stack:=[]*Tree{}
current:=t
for current!=nil || len(stack)>0{
for current!=nil{
stack = append(stack, current)
current = current.Left
}
current = stack[len(stack)-1]
stack = stack[:len(stack)-1]
k--
if k==0{
return current.Value.(int)
}
current = current.Right
}
return -1
}
</CH.Section>