# [LeetCode] 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<vector<int>> zigzagLevelOrder(TreeNode* root) {
if (!root) return {};
vector<vector<int>> res;
queue<TreeNode*> q{{root}};
int cnt = 0;
while (!q.empty()) {
vector<int> oneLevel;
for (int i = q.size(); i > 0; --i) {
TreeNode *t = q.front(); q.pop();
oneLevel.push_back(t->val);
if (t->left) q.push(t->left);
if (t->right) q.push(t->right);
}
if (cnt % 2 == 1) reverse(oneLevel.begin(), oneLevel.end());
res.push_back(oneLevel);
++cnt;
}
return res;
}
};

class Solution {
public:
vector<vector<int>> zigzagLevelOrder(TreeNode* root) {
if (!root) return {};
vector<vector<int>> res;
queue<TreeNode*> q{{root}};
bool leftToRight = true;
while (!q.empty()) {
int size = q.size();
vector<int> oneLevel(size);
for (int i = 0; i < size; ++i) {
TreeNode *t = q.front(); q.pop();
int idx = leftToRight ? i : (size - 1 - i);
oneLevel[idx] = t->val;
if (t->left) q.push(t->left);
if (t->right) q.push(t->right);
}
leftToRight = !leftToRight;
res.push_back(oneLevel);
}
return res;
}
};

class Solution {
public:
vector<vector<int>> zigzagLevelOrder(TreeNode* root) {
vector<vector<int>> res;
helper(root, 0, res);
return res;
}
void helper(TreeNode* node, int level, vector<vector<int>>& res) {
if (!node) return;
if (res.size() <= level) {
res.push_back({});
}
vector<int> &oneLevel = res[level];
if (level % 2 == 0) oneLevel.push_back(node->val);
else oneLevel.insert(oneLevel.begin(), node->val);
helper(node->left, level + 1, res);
helper(node->right, level + 1, res);
}
};

Github 同步地址：

https://github.com/grandyang/leetcode/issues/103

Binary Tree Level Order Traversal

https://leetcode.com/problems/binary-tree-zigzag-level-order-traversal/

https://leetcode.com/problems/binary-tree-zigzag-level-order-traversal/discuss/33815/My-accepted-JAVA-solution

https://leetcode.com/problems/binary-tree-zigzag-level-order-traversal/discuss/33825/c%2B%2B-5ms-version%3A-one-queue-and-without-reverse-operation-by-using-size-of-each-level

LeetCode All in One 题目讲解汇总(持续更新中...)

posted @ 2015-02-21 14:55  Grandyang  阅读(12693)  评论(7编辑  收藏  举报