Neat C++ code that beats 100% submissions


  • 0
    A
    Using two stacks to store the levels of the tree in turns, and one stack stores left son firstly, whereas the other stack stores right son firstly.
    This is my code:
    

    class Solution {
    public:
    vector<vector<int>> zigzagLevelOrder(TreeNode* root) {
    vector<vector<int> > res;
    if(root==NULL)
    return res;
    stack<TreeNode*> s[2];
    int index=0;
    s[index].push(root);
    while(s[index].size())
    {
    vector<int> line;
    while(s[index].size())
    {
    root=s[index].top();
    s[index].pop();
    line.push_back(root->val);
    if(index==0)
    {
    if(root->left)
    s[1-index].push(root->left);
    if(root->right)
    s[1-index].push(root->right);
    }
    else
    {
    if(root->right)
    s[1-index].push(root->right);
    if(root->left)
    s[1-index].push(root->left);
    }
    }
    res.push_back(line);
    index=1-index;
    }
    return res;

    }
    

    };


Log in to reply
 

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