binary Tree Zigzag level order

//103. Binary Tree Zigzag Level Order Traversal
Given a binary tree, return the zigzag level order traversal of its nodes' values. (ie, from left to right, then right to left for the next level and alternate between).

For example:
Given binary tree [3,9,20,null,null,15,7],
3
/
9 20
/
15 7
return its zigzag level order traversal as:
[
[3],
[20,9],
[15,7]
]

class Solution {
public:
    vector> zigzagLevelOrder(TreeNode* root) {
        vector> res;
        if(root==NULL){
            return res;
        }

        queue> q;
        q.push(make_pair(root,0));
        while(!q.empty()){
            TreeNode* node=q.front().first;
            int level=q.front().second;
            q.pop();

            if(res.size()==level){
                res.push_back(vector());
            }

            assert(levelval);
            if(node->left){
                q.push(make_pair(node->left,level+1));
            }
            if(node->right){
                q.push(make_pair(node->right,level+1));
            }
        }
        for(int i=0;i1){
                    reverse(res[i].begin(),res[i].end());
                }
            }

        return res;
    }
};

你可能感兴趣的:(binary Tree Zigzag level order)