题目描述
题目来源
题目解析
我们都知道二叉搜索树的中序遍历是有序的,有一种方式就是把二叉搜索树中序遍历的结果存放到一个数组中,因为这个数组是升序的(虽然有重复的),我们可以遍历这个数组,这里使用几个变量
使用变量curent表示当前的值,count表示当前值的数量,maxCount表示重复数字最大的数量。list集合存放结果
1,如果节点值等于curent,count就加1,
2,如果节点不等于current,说明遇到了下一个新的值,更新current为新的值,然后让count=1;
接着比较count和maxCount的大小,
- 如果count==maxCount,就把当前节点的值加入到集合list中(遇到的值一定是个新值)。
- 如果count>maxCount,先把list集合清空,然后再把当前节点的值加入到集合list中,最后在更新maxCount的值。
private TreeNode pre;
private int curCount = 0;
private int maxCount = 0;
private ArrayList<Integer> list = new ArrayList<Integer>();
public int[] findMode(TreeNode root) {
helper(root);
return list.stream().mapToInt(Integer::intValue).toArray() ;
}
private void helper(TreeNode root){
if (root == null){
return;
}
helper(root.left);
if (pre == null || pre.val != root.val){
curCount = 1;
}else {
curCount++;
}
if (curCount == maxCount){
list.add(root.val);
}else if (curCount > maxCount){
maxCount = curCount;
list.clear();;
list.add(root.val);
}
pre = root;
helper(root.right);
}
class Solution {
public:
// 树中节点的数目在范围 [1, 104] 内
vector<int> findMode(TreeNode* root) {
helper(root);
return vec;
}
private:
TreeNode* pre;
vector<int> vec;
int maxCount, currCount;
private:
void helper(TreeNode* root){
if(root == NULL){
return;
}
helper(root->left);
if(pre == NULL || pre->val != root->val){
currCount = 1;
}else{
currCount++;
}
if(currCount == maxCount){
vec.emplace_back(root->val);
}else if(currCount > maxCount){
vec.clear();
maxCount = currCount;
vec.emplace_back(root->val);
}
pre = root;
helper(root->right);
}
};