103. Binary Tree Zigzag Level Order Traversa

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/hdjiguangxi/article/details/89212195

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<vector<int>> zigzagLevelOrder(TreeNode* root) {
        vector<vector<int>> vec;
        queue<TreeNode*>que;
        que.push(root);
        if(root==NULL){
            return vec;
        }
        //一次入一层,出一层 
        int dep=0,num=1,last=1;
        while(!que.empty()){
            int size=que.size();
            vector<int>vv;
            for(int i=0;i<size;i++){
                TreeNode* p=que.front();
                que.pop();
                if(p){
                vv.push_back(p->val);
                if(p->left)
                    que.push(p->left);
                if(p->right)
                    que.push(p->right);
                }
            }
            if(dep%2==1){
                for(int i=0,j=vv.size()-1;i<j;i++,j--)
                    swap(vv[i],vv[j]);
            }
            vec.push_back(vv);
            dep++;
        }
        return vec;
    }
};

猜你喜欢

转载自blog.csdn.net/hdjiguangxi/article/details/89212195