501 Find Mode in Binary Search Tree

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

C++:

method one:

/**
 * 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);
    }
};

 Method Two:

/**
 * 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;
    }
};

 Reference: http://www.cnblogs.com/grandyang/p/6436150.html

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324691908&siteId=291194637