【題目】501. 二叉搜索樹中的衆數
給定一個有相同值的二叉搜索樹(BST),找出 BST 中的所有衆數(出現頻率最高的元素)。
假定 BST 有如下定義:
結點左子樹中所含結點的值小於等於當前結點的值
結點右子樹中所含結點的值大於等於當前結點的值
左子樹和右子樹都是二叉搜索樹
例如:
給定 BST [1,null,2,2],
1
\
2
/
2
返回[2].
提示:如果衆數超過1個,不需考慮輸出順序
進階:你可以不使用額外的空間嗎?(假設由遞歸產生的隱式調用棧的開銷不被計算在內)
【解題思路1】中序遍歷+List存衆數
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
private List<Integer> modes;
private int cur;
private int curTimes;
private int lastTimes;
public int[] findMode(TreeNode root) {
modes = new LinkedList<>();
inOrder(root);
int[] res = new int[modes.size()];
for(int i = 0; i < modes.size(); i++)
res[i] = modes.get(i);
return res;
}
private void inOrder(TreeNode root) {
if(root == null) return;
inOrder(root.left);
if(lastTimes == 0)
lastTimes = 1;
if(root.val != cur)
curTimes = 0;
cur = root.val;
curTimes++;
if(curTimes == lastTimes)
modes.add(cur);
if(curTimes > lastTimes){
lastTimes = curTimes;
modes.clear();
modes.add(cur);
}
inOrder(root.right);
}
}