Given a binary search tree (BST) with duplicates, find all the mode(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).
Subscribe to see which companies asked this question.
思路:我的这个方法用了很多额外的控件,但是比较好理解,先终于遍历将节点存入map里面,value值为那个值的个数,在找出value最大的值,对应的key存入数组。
public class Solution {
public int[] findMode(TreeNode root) {
int[] a = new int[] {};
List<Integer> list = new ArrayList<>();
Map<Integer, Integer> map = new HashMap<>();
Stack<TreeNode> stack = new Stack<>();
while (!stack.isEmpty() || root != null) {
while (root != null) {
stack.push(root);
root = root.left;
}
root = stack.pop();
map.put(root.val, map.getOrDefault(root.val, 0) + 1);
root = root.right;
}
int max = 0;
Iterator iter = map.entrySet().iterator();
while (iter.hasNext()) {
Map.Entry entry = (Map.Entry) iter.next();
int val = (int) entry.getValue();
if (val > max) {
max = val;
}
}
iter = map.entrySet().iterator();
while (iter.hasNext()) {
Map.Entry entry = (Map.Entry) iter.next();
int key = (int) entry.getKey();
int val = (int) entry.getValue();
if (val == max) {
list.add(key);
}
}
a = new int[list.size()];
for (int i = 0; i < list.size(); i++) {
a[i] = list.get(i);
}
return a;
}
}
可以看到,对象多了后,时间也是好长。。。
看到答案的一种方法就是用递归,在递归的时候记录个数,因为二叉搜索树中序遍历的话是有序的如果相同则会在前后一起,同时记录前一个节点的值,并和当前节点的值比较,如果个数大于了当前的max(相同值的节点的数量),则list先清除之前插入的,然后插入当前节点的值。