欢迎来到PJCK的博客

(二叉树 BFS) leetcode103. 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]
]

---------------------------------------------------------------------------------------------------------------------

这个是在leetcode102. Binary Tree Level Order Traversal的基础上拓展来的,只要加一个判断就行。

C++代码:

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    vector<vector<int>> zigzagLevelOrder(TreeNode* root) {
        if(!root) return {};
        queue<TreeNode*> q;
        q.push(root);
        vector<vector<int> > vec;
        bool flag = true;
        while(!q.empty()){
            vector<int> v;
            for(int i = q.size(); i > 0; i--){
                auto t = q.front();
                q.pop();
                v.push_back(t->val);
                if(t->left) q.push(t->left);
                if(t->right) q.push(t->right);
            }
            if(!flag)
                    reverse(v.begin(),v.end());
            flag = !flag;
            vec.push_back(v);
        }
        return vec;
    }
};

 

posted @ 2019-04-29 20:32  PJCK  阅读(88)  评论(0编辑  收藏  举报