Leetcode 501 - Find Mode in Binary Search Tree(BST求众数)

16 篇文章 0 订阅

题意

给一个BST,求val值的众数(可能有多个)

follow up:能否只用 O(1) 空间呢?(二叉树遍历过程中的栈空间不计入)

思路

算法1

O(n) 时间, O(n) 空间

遍历二叉树,并且用一个vis[]数组来记录每个数出现了多少次。为了避免vis[]太大爆内存,可用unordered_map替代

算法2

O(n) 时间, O(1) 空间

我们知道BST一个很重要的性质就是:其中序遍历结果是一个升序数组

对一个有序数组,求他的众数我们只需要遍历2遍统计结果即可

该题也只需要先对BST中序遍历一遍求出众数对应的出现次数是多少,再遍历一遍去统计结果即可

代码

算法1
/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
private:
    unordered_map<int, int> vis;
    vector<int> ans;
    int _max = 0;
public:
    void dfs(TreeNode* root) {
        if (!root) return;
        vis[root->val]++;
        if (vis[root->val] > _max) _max = vis[root->val];
        dfs(root->left);
        dfs(root->right);
    }

    vector<int> findMode(TreeNode* root) {
        _max = 0;
        dfs(root);
        for (auto it = vis.begin(); it != vis.end(); it++) {
            if (it->second == _max) ans.push_back(it->first);
        }
        return ans;
    }
};
算法2
/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
private:
    int max_;
    int pre, count;
        bool flag;
    vector<int> ans;

    void reset() {
        flag = 0;
        count = 0;
    }

    void cal(int x, int sta) {
        if (!flag) {
            if (!sta) max_ = 1;
            pre = x;
            count++;
            if (sta && count == max_) ans.push_back(x);
            flag = true;
        } else {
            if (pre == x) {
                count++;
                if (!sta && count > max_) max_ = count;
                if (sta && count == max_) ans.push_back(x);
            } else {
                count = 1;
                pre = x;
                if (sta && count == max_) ans.push_back(x);
            }
        }
    }

    void inorder(TreeNode* root, int sta) {
        if (!root) return;
        inorder(root->left, sta);
        cal(root->val, sta);
        inorder(root->right, sta);
    }

public:
    Solution() : max_(0), pre(-1), count(0), flag(false) {}
    vector<int> findMode(TreeNode* root) {
        inorder(root, 0);
        reset();
        inorder(root, 1);
        return ans;
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值