您的位置:首页 > 其它

Binary Tree Zigzag Level Order Traversal

2015-06-19 23:33 274 查看
Description:

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,#,#,15,7}
,

3
/ \
9  20
/  \
15   7


return its zigzag level order traversal as:

[
[3],
[20,9],
[15,7]
]

Code:

vector<vector<int>> zigzagLevelOrder(TreeNode* root) {
deque<TreeNode*>a;
deque<TreeNode*>b;
if (root)
a.push_back(root);

TreeNode*p = NULL;
vector<vector<int>> result;

while (!a.empty() || !b.empty())
{
vector<int>temp;
if (!a.empty() )
{
while (!a.empty() )
{
p = a.front();
a.pop_front();
temp.push_back(p->val);
if (p->left)
b.push_back(p->left);
if (p->right)
b.push_back(p->right);
}
result.push_back(temp);
}
else
{
while (!b.empty())
{
p = b.front();
b.pop_front();
temp.push_back(p->val);
if (p->left)
a.push_back(p->left);
if (p->right)
a.push_back(p->right);
}
result.push_back(temp);
}
}
for (int i = 1; i < result.size(); i+=2)
{
reverse(result[i].begin(),result[i].end());
}
return result;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: