Given a binary search tree (BST) with duplicates, find all themode(s)(the most frequently occurred element) in the given BST.
Assume a BST is defined as follows:
- The left subtree of a node contains only nodes with keys less than or equal to the node's key.
- The right subtree of a node contains only nodes with keys greater than or equal to the node's key.
- Both the left and right subtrees must also be binary search trees.
For example:
Given BST[1,null,2,2]
,
1
\
2
/
2
return[2]
.
Note:If a tree has more than one mode, you can return them in any order.
Follow up:Could you do that without using any extra space? (Assume that the implicit stack space incurred due to recursion does not count).
Solution:
//O(n) space: hashmap
//O(1) space: in-order traversal, 记录之前的node的val,如果当前root.val与它相等,count++,否则count=1。然后count于max比较,若大于max,则清空list,然后加入root.val。
Integer prev;
int max = 0;
int count = 1;
public int[] findMode(TreeNode root) {
if(root == null){
return new int[0];
}
List<Integer> list = new ArrayList<Integer>();
traverse(root, list);
int[] ans = new int[list.size()];
for(int i = 0; i < ans.length; i++){
ans[i] = list.get(i);
}
return ans;
}
private void traverse(TreeNode root, List<Integer> list){
if(root == null){
return;
}
traverse(root.left, list);
if(prev != null){
if(root.val == prev){
count++;
} else{
count = 1;
}
}
if(count > max){
max = count;
list.clear();
list.add(root.val);
} else if(count == max){
list.add(root.val);
}
prev = root.val;
traverse(root.right, list);
}