# 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]
]


/**
* 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) {
vector<vector<int> > outer;
vector<int> inner;
queue<TreeNode*> q;
if (root)
q.push(root);
else
return outer;
int k=1;
while (!q.empty())
{
int size=q.size();
inner.clear();
while (size-->0)
{
TreeNode* t=q.front();
q.pop();
inner.push_back(t->val);
if (t->left)
q.push(t->left);
if (t->right)
q.push(t->right);
}
if (k%2)
outer.push_back(inner);
else
{
reverse(inner.begin(),inner.end());
outer.push_back(inner);
}
k++;
}
return outer;
}
};

• 本文已收录于以下专栏：

举报原因： 您举报文章：103. Binary Tree Zigzag Level Order Traversal 色情 政治 抄袭 广告 招聘 骂人 其他 (最多只允许输入30个字)