LeetCode Find Mode in BST

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.

Solution 1(菜鸟解法):

vector<int> findMode(TreeNode* root) {
        vector<int> key;
        midTraversal(root, key);
        int maxKey, time = 0;
        int i = 0;
        while(i < key.size()) {
            int tmpTime = 1;
            while(i+1 < key.size() && key[i+1] == key[i]){
                i++;
                tmpTime++;
            }
            if(tmpTime > time){
                maxKey = key[i];
                time = tmpTime;
            }
            i++;
        }
        i = 0;
        int index = 0;
        while(i < key.size()){
            int tmpTime = 1;
            while(i+1 < key.size() && key[i+1] == key[i]){
                i++;
                tmpTime++;
            }
            if(tmpTime == time){
                key[index++] = key[i];
            }
            i++;
        }
        key.erase(key.begin() + index, key.end());
        return key;
    }
    void midTraversal(TreeNode* root, vector<int>& key) {
        if(root == NULL) return;
        midTraversal(root->left, key);
        key.push_back(root->val);
        midTraversal(root->right, key);
    }

思路:递归求出中序遍历数组,然后扫描数组找出最大次数,再求出满足题意的元素。
可以优化成以下解法(无需把中序遍历的次序完整存到数组中,用一个cnt维护)
Solution 2:

vector<int> findMode(TreeNode* root) {
        vector<int> res;
        int cnt = 0;
        TreeNode* pre = NULL;
        int gmax = -1;
        helper(root, res, pre, cnt, gmax);
        return res;
    }
    void helper(TreeNode* root, vector<int>& res, TreeNode*& pre, int& cnt, int& gmax) {
        if(root == NULL) return;
        helper(root->left, res, pre, cnt, gmax);
        if(pre) cnt = (root->val == pre->val) ? cnt+1: 1;
        else cnt = 1;
        if(cnt >= gmax){
            if(cnt > gmax)
                res.clear();
            res.push_back(root->val);
            gmax = cnt;
        }
        pre = root;
        helper(root->right, res, pre, cnt, gmax);
    }
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • 背景 一年多以前我在知乎上答了有关LeetCode的问题, 分享了一些自己做题目的经验。 张土汪:刷leetcod...
    土汪阅读 14,358评论 0 33
  • 326. Power of Three Given an integer, write a function to...
    跑者小越阅读 6,488评论 0 1
  • 细雨霏霏落窗前, 孤灯瘦影对愁眠, 风霜频临催人老, 叶落清秋无人怜。 晓风残月杨柳岸, 欲眼望穿君不还!
    文卷阅读 1,526评论 0 5
  • 人们总爱回忆过去,并不是因为过去美好,而是因为过去再也回不去了。我们大多数人都已经习惯无谓的挣扎,就好像所有的结局...
    北面环岛阅读 2,224评论 0 1

友情链接更多精彩内容