Find Mode in Binary Search Tree (the most frequently occurred element) cpp, leetcode

 Find Mode in Binary Search Tree (the most frequently occurred element) cpp, leetcode

---------------------------------------------------------------------------------------------------------------


Given a binary search tree (BST) with duplicates, find all the mode(s) (the most frequently occurred element) in the given BST.

For example:
Given BST [1,null,2,2],

   1
    \
     2
    /
   2

 

return [2].

=============================================

 

 
class Solution {
public:
    vector<int> findMode(TreeNode* root)
    {
        stack<TreeNode* >s;
        map<int,int>m;
        vector<int>v;
        int maxm=INT_MIN;
        
        if(root==NULL)
            return v;
        
        s.push(root);
        root=root->left;
        while(1)
        {
            
            while(root)
            {
                s.push(root);
                root=root->left;
            }
            if(s.empty())
                break;
            root=s.top();
            s.pop();
            m[root->val]++;
            
            root=root->right;
        }
        
        for(auto x:m)
            maxm=max(maxm,x.second);
        for(auto x:m)
        {
            if(x.second==maxm)
                v.push_back(x.first);
        }
        
        return v;
        
        
    }
};

 

Comments

Popular posts from this blog

Amazing Subarrays(cpp,interviewbit)

Symmetric Tree(leetcode,cpp):

sum of left leaves in a tree(leetcode).