# 103. Binary Tree Zigzag Level Order Traversal

47人阅读 评论(0)

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>> result;
if(root==NULL) return result;

queue<TreeNode*> layer;
layer.push(root);

bool ifReverse = false;
while(!layer.empty())
{
int num = layer.size();
vector<int> layerRes;

for(int i = 0; i  < num; i++)
{
TreeNode* node = layer.front();
layer.pop();
layerRes.push_back(node->val);

if(node->left != NULL)
{
layer.push(node->left);
}

if(node->right != NULL)
{
layer.push(node->right);
}
}
if(ifReverse)
{
reverse(layerRes.begin(), layerRes.end());
ifReverse = false;
}
else
{
ifReverse = true;
}

result.push_back(layerRes);
}

return result;
}
};

0
0

* 以上用户言论只代表其个人观点，不代表CSDN网站的观点或立场
个人资料
• 访问：69013次
• 积分：0
• 等级：
• 排名：千里之外
• 原创：146篇
• 转载：8篇
• 译文：0篇
• 评论：5条
评论排行
最新评论