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).
给出一棵二叉搜索数,输出它的众数,即出现次数最多的数,可能有重复元素,众数有多个时,可按任意顺序输出。
思路:
如果是数组中找相同元素出现的次数,最简单的方法是排序,然后按顺序遍历数组。
而二叉搜索树有一个特点,就是中序遍历的输出就是排序后的数组。
可以把中序遍历结果保存在一个数组中,然后查找每个元素出现的次数。
而follow up中指出可以不用额外的存储空间,
因为中序遍历是按从小到大的顺序的,所以相同的元素必然会连续访问。这时可以用一个TreeNode记录下前一个node,用一个count记录下当前元素出现的次数,maxCount记录下最多出现元素的次数。
如果前一个node为null或者前一个node的值不等于当前node的值,count就要重置为1,如果前一个node的值等于当前node值,则count++。
然后count与maxCount相比,如果和maxCount一样,那么直接把值添加进结果的list中,大于maxCount时就说明当前node的值是众数,要把之前list中的结果全部删除,再添加当前值。
//0ms
class Solution {
TreeNode pre = null;
int cnt = 0;
int maxCnt = 0;
public int[] findMode(TreeNode root) {
if (root == null) {
return new int[]{};
}
ArrayList<Integer> list = new ArrayList<>();
inOrder(root, list);
int[] result = new int[list.size()];
for(int i = 0; i < list.size(); i++) {
result[i] = list.get(i);
}
return result;
}
public void inOrder(TreeNode root, ArrayList<Integer> list) {
if(root == null) {
return;
}
inOrder(root.left, list);
if(pre == null || pre.val != root.val) {
cnt = 1;
} else {
cnt ++;
}
if(cnt > maxCnt) {
list.clear();
list.add(root.val);
} else if(cnt == maxCnt) {
list.add(root.val);
}
pre = root;
maxCnt = Math.max(cnt, maxCnt);
inOrder(root.right, list);
}
}