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.
问题不复杂,就是一个遍历加map的问题
基本做法如下
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
int max = 0;
public int[] findMode(TreeNode root) {
if(root == null){
return new int[0];
}
Map<Integer, Integer> map = new HashMap<>();
helper(map, root);
List<Integer> list = new LinkedList<>();
for(int key: map.keySet()){
if(map.get(key) == max) list.add(key);
}
int[] res = new int[list.size()];
for(int i = 0; i<res.length; i++) res[i] = list.get(i);
return res;
}
private void helper(Map<Integer, Integer> map, TreeNode root){
if(root == null){
return;
}
if(map.containsKey(root.val)){
map.put(root.val, map.get(root.val) + 1);
}else{
map.put(root.val, 1);
}
max = Math.max(max, map.get(root.val));
helper(map, root.right);
helper(map, root.left);
}
}
当然,我写完之后,发现大大的做法还是让人跪服 O(1)的space啊
319




被折叠的 条评论
为什么被折叠?



