/*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]
]
*/
//思路:使用双段队列
//设置层次,如果是奇数层,从左往右
//如果偶数层,从右往左(左右指针相同)
#include <iostream>
#include <vector>
#include <deque>
struct TreeNode
{
int val;
TreeNode* left;
TreeNode* right;
TreeNode(int x):val(x),left(NULL),right(NULL){}
};
class Solution
{
public:
std::vector<std::vector<int> > zigzagLevelOrder(TreeNode* root)
{
std::vector<std::vector<int> > vec;
if(root==NULL)
return vec;
int level=1; //odd or ....
int count;
TreeNode* tem;
std::deque<TreeNode*> deque;
deque.push_back(root);
while(!deque.empty())
{
count=deque.size();
std::vector<int> lv;
if(level%2==0)//from right to left;
{
while(count--)
{
tem=deque.back();
deque.pop_back();
lv.push_back(tem->val);
if(tem->right!=NULL)
deque.push_front(tem->right);
if(tem->left!=NULL)
deque.push_front(tem->left);
}
vec.push_back(lv);
}
else //from left to right
{
while(count--)
{
tem=deque.front();
deque.pop_front();
lv.push_back(tem->val);
if(tem->left!=NULL)
deque.push_back(tem->left);
if(tem->right!=NULL)
deque.push_back(tem->right);
}
vec.push_back(lv);
}
++level;
}
return vec;
}
};
int main(int argc,char* argv[])
{
return 0;
}
锯齿状层次化输出二叉树
最新推荐文章于 2021-08-19 22:45:29 发布
本文介绍了一种实现二叉树锯齿形层次遍历的方法,使用双端队列并根据层次的奇偶性调整遍历方向。通过创建一个`Solution`类,并在`zigzagLevelOrder`函数中,当层次为偶数时从右到左遍历,为奇数时从左到右遍历,从而达到锯齿状层次遍历的效果。
摘要由CSDN通过智能技术生成