C++. 8ms Iterative (queue+stack)


  • 1
    H
    /**
     * 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<vector<int>> levelOrderBottom(TreeNode* root) {
            vector<vector<int>> nodes;
            if(!root)
                return nodes;
                
            stack<vector<int>> s;
            queue<TreeNode*> q;
            q.push(root);
            
            while(1){
                int nodecount = q.size();
                vector<int> levelnodes;
                if(nodecount == 0)
                    break;
                
                while(nodecount > 0){
                    TreeNode *p = q.front();
                    q.pop();
                    levelnodes.push_back(p->val);
                    nodecount--;
                    if(p->left)
                        q.push(p->left);
                    if(p->right)
                        q.push(p->right);
                }
                // one level complete
                s.push(levelnodes);
            }
            // now push elements to the nodes vector
            while(s.size()){
                nodes.push_back(s.top());
                s.pop();
            }
    
            
            return nodes;
    
        }    
    };`
    

    May be this solution has been discussed before.
    We can use stack to reverse the elements.


  • 0
    B

    this algorithm is not so good;
    I don't want extra space to store the vector<int>


Log in to reply
 

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