I just want to know where was my code wrong? I want use two stacks to implement it.


  • 0
    U

    class Solution {
    public:
    vector<vector<int> > zigzagLevelOrder(TreeNode *root) {
    vector<vector<int>> result;
    if(root==nullptr) return result;
    vector<int> layer;
    stack<TreeNode *> current, next;
    bool leftToRight=true;
    current.push(root);
    while(!current.empty()){
    TreeNode *tmp = current.top();

            current.pop();
            if(tmp){
                
            layer.push_back(tmp->val);
            if(leftToRight){
                next.push(tmp->left);
                next.push(tmp->right);
            }else{
                next.push(tmp->right);
                next.push(tmp->left);
            }
              
            }else{
                if(current.empty()){
                result.push_back(layer);
                leftToRight=!leftToRight;
                swap(current, next);
            }
            }
             
        }
        
        return result;
    }
    

    };


  • 0
    L

    next.push(tmp->left);
    how ccan u sure tmp have left or right child?


Log in to reply
 

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