zoukankan      html  css  js  c++  java
  • 501 Find Mode in Binary Search Tree

    详见:https://leetcode.com/problems/find-mode-in-binary-search-tree/description/

    C++:

    方法一:

    /**
     * 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 {
    public:
        vector<int> findMode(TreeNode* root)
        {
            vector<int> res;
            int mx=0;
            unordered_map<int,int> m;
            inorder(root,mx,m);
            for(auto &a:m)
            {
                if(a.second==mx)
                {
                    res.push_back(a.first);
                }
            }
            return res;
        }
        void inorder(TreeNode* node,int &mx,unordered_map<int,int> &m)
        {
            if(!node)
            {
                return;
            }
            inorder(node->left,mx,m);
            mx=max(mx,++m[node->val]);
            inorder(node->right,mx,m);
        }
    };
    

     方法二:

    /**
     * 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 {
    public:
        vector<int> findMode(TreeNode* root) 
        {
            if (!root)
            {
                return {};
            }
            vector<int> res;
            TreeNode *p = root, *pre = nullptr;
            stack<TreeNode*> s;
            int mx = 0, cnt = 1;;
            while (!s.empty() || p) {
                while (p)
                {
                    s.push(p);
                    p = p->left;
                }
                p = s.top();
                s.pop();
                if (pre)
                {
                    cnt = (p->val == pre->val) ? cnt + 1 : 1;
                }
                if (cnt >= mx)
                {
                    if (cnt > mx) 
                    {
                        res.clear();
                    }
                    res.push_back(p->val);
                    mx = cnt;
                }
                pre = p;
                p = p->right;
            }
            return res;
        }
    };
    

     参考:http://www.cnblogs.com/grandyang/p/6436150.html

  • 相关阅读:
    札记:计算机网络篇:物理层
    vs2012 它已停止工作
    php laravel 帧 该文件上传
    2016第一周日
    2015年第1周六
    2016第1周五优化自己
    2016值得关注的语言平台、JS框架
    JS模块化规范CommonJS,AMD,CMD
    2016第1周二
    ReactJS入门教程
  • 原文地址:https://www.cnblogs.com/xidian2014/p/8906340.html
Copyright © 2011-2022 走看看