二叉搜索树中的众数

LeetCode | 501.二叉搜索树中的众数

给你一个含重复值的二叉搜索树(BST)的根节点 root ,找出并返回 BST 中的所有 众数(即,出现频率最高的元素)。

如果树中有不止一个众数,可以按 任意顺序 返回。

假定 BST 满足如下定义:

  • 结点左子树中所含节点的值 小于等于 当前节点的值
  • 结点右子树中所含节点的值 大于等于 当前节点的值
  • 左子树和右子树都是二叉搜索树
示例 1:
    1
     \
      2
     /
    2  
输入:root = [1,null,2,2]
输出:[2]
示例 2:

输入:root = [0]
输出:[0]

提示:

  • 树中节点的数目在范围 [1, 104] 内
  • -105 <= Node.val <= 105

用 mirrors 算法进行中序遍历,遍历的结果是从小到大非严格递增的。对遍历到的结果用 update 函数进行判断。

int maxCount = 0;
int last = 1000000;
vector<int> findMode(TreeNode* root) {
    vector<int> res;
    int count = 0;
    while (root) {
        if (root->left) {
            TreeNode* rightmost = root->left;
            while (rightmost->right && rightmost->right != root) {
                rightmost = rightmost->right;
            }
            if (rightmost->right) {
                update(count, root->val, res);
                rightmost->right = nullptr;
                root = root->right;
            } else {
                rightmost->right = root;
                root = root->left;
            }
        } else {
            update(count, root->val, res);
            root = root->right;
        }
    }
    return res;
}
void update(int &count, int value, vector<int> &res) {
    if (value == last) {
        count++;
    } else {
        count = 0;
        last = value;
    }
    if (count == maxCount) {
        res.push_back(value);
    } else if (count > maxCount) {
        maxCount = count;
        res.clear();
        res.push_back(value);
    }
}
posted @ 2023-04-03 16:03  卑以自牧lq  阅读(35)  评论(0)    收藏  举报