给定一个二叉树,返回其节点值的锯齿形层次遍历。(即先从左往右,再从右往左进行下一层遍历,以此类推,层与层之间交替进行)。
例如:
给定二叉树 [3,9,20,null,null,15,7]
,
3
/ \
9 20
/ \
15 7
返回锯齿形层次遍历如下:
[
[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>>v;
vector<int>v1;
TreeNode* t=root;
if(t==NULL)
{
return v;
}
queue<TreeNode*>q;
q.push(t);
int i=0;
while (!q.empty())
{
v1.clear();
int Size=q.size();
i++;
for (int j=0;j<Size;j++)
{
TreeNode* temp=q.front();
q.pop();
if(temp->left)
{
q.push(temp->left);
}
if(temp->right)
{
q.push(temp->right);
}
v1.push_back(temp->val);
}
if(i%2==0)
reverse(v1.begin(),v1.end());
v.push_back(v1);
}
return v;
}
};