美文网首页
binary-tree-zigzag-level-order-t

binary-tree-zigzag-level-order-t

作者: DaiMorph | 来源:发表于2019-05-03 18:39 被阅读0次
    class Solution {
    public:
        vector<vector<int> > zigzagLevelOrder(TreeNode *root) {
            vector<vector<int>>ans;
            queue<TreeNode*>cur,nex;
            if(!root)return ans;
            cur.push(root);
            int level=1;
            while(!cur.empty())
            {
                vector<int>temp;
                while(!cur.empty())
                {
                    TreeNode*top=cur.front();
                    cur.pop();
                    temp.push_back(top->val);
                    if(top->left)nex.push(top->left);
                    if(top->right)nex.push(top->right);
                }
                swap(cur,nex);
                if(level%2==0)reverse(temp.begin(),temp.end());
                level++;
                ans.push_back(temp);
            }
            return ans;
        }
    };
    
    
    class Solution {
    public:
        vector<vector<int> > zigzagLevelOrder(TreeNode *root) {
            vector<vector<int>>ans;
            queue<TreeNode*>q;
            int level=1;
            if(!root)return ans;
            q.push(root);
            while(!q.empty())
            {
                vector<int>temp;
                int size=q.size();
                while(size--)
                {
                    TreeNode*top=q.front();
                    q.pop();
                    temp.push_back(top->val);
                    if(top->left)q.push(top->left);
                    if(top->right)q.push(top->right);
                }
                if(level%2==0)reverse(temp.begin(),temp.end());
                level++;
                ans.push_back(temp);
            }
            return ans;
        }
    };
    

    相关文章

      网友评论

          本文标题:binary-tree-zigzag-level-order-t

          本文链接:https://www.haomeiwen.com/subject/qoianqtx.html