4ms c++


  • 0
    B
    class Solution {
    public:
        vector< vector<int> > zigzagLevelOrder(TreeNode* root) {
            vector< vector<int> >ans;
            vector<int> tmp;
            if (root==NULL) return ans;
            vector< vector<TreeNode*> > mid;
            int flag = 1;
            mid.resize(2);
            mid[0].push_back(root);
            mid[1].push_back(root);
            tmp.push_back(root->val);
            ans.push_back(tmp);
            for(;;)
            {
                if (mid[flag].size()==0) break;
                int now = 1 - flag;
                mid[now].clear();
                tmp.clear();
                for(int i=0;i<mid[flag].size();i++)
                {
                    TreeNode* p=mid[flag][i];
                    if (p->left!=NULL) mid[now].push_back(p->left);
                    if (p->right!=NULL) mid[now].push_back(p->right);
                }
                if (flag==1)
                {
                    for(int i=mid[now].size()-1;i>=0;i--)
                        tmp.push_back(mid[now][i]->val);
                }
                else
                {
                    for(int i=0;i<mid[now].size();i++)
                        tmp.push_back(mid[now][i]->val);
                }
                if (tmp.size()!=0) ans.push_back(tmp);
                flag = 1-flag;
            }
        }
    };
    

Log in to reply
 

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