c++ in-order non-recursive solution


  • 0
    vector<int> findMode(TreeNode* root) 
    {
        vector<int> result;
        unordered_map<int, int> maps;
        stack<struct TreeNode*> nodes;
        int count = 0;
        struct TreeNode* visit = root;
        
        while (!nodes.empty() || (visit != NULL))
        {
            if (visit != NULL)
            {
                nodes.push(visit);
                visit = visit->left;
            }
            else
            {
                visit = nodes.top();
                nodes.pop();
                maps[visit->val]++;
                count = max(count, maps[visit->val]);
                visit = visit->right;
            }
        }
        
        for (auto elem : maps)
        {
            if (elem.second == count)
            {
                result.push_back(elem.first);
            }
        }
        
        return result;
    }

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.