4ms c++ solution using two stacks


  • 0
    vector<vector<int>> zigzagLevelOrder(TreeNode* root) {
            vector<vector<int>> res;
            if(root==NULL) return res;
            stack<TreeNode*> s, sub;
            s.push(root);
            TreeNode* t;
            bool leftToRight = true;
            while(!s.empty())
            {
                vector<int> arow;
                while(!s.empty())
                {
                    t = s.top();
                    s.pop();
                    arow.push_back(t->val);
                    if(leftToRight)
                    {
                        if(t->left)  sub.push(t->left);
                        if(t->right) sub.push(t->right);
                    } 
                    else
                    {
                        if(t->right) sub.push(t->right);
                        if(t->left)  sub.push(t->left);
                    }
                }
                leftToRight = !leftToRight;
                res.push_back(arow);
                s.swap(sub);
            }
            return res;
        }
    

Log in to reply
 

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