给出一棵二叉树,返回其节点值的锯齿形层次遍历(先从左往右,下一层再从右往左,层与层之间交替进行)
给出一棵二叉树 {3,9,20,#,#,15,7}
返回其锯齿形的层次遍历为:
[
[3],
[20,9],
[15,7]
]
基本思想与二叉树的层次遍历一致,只不过隔行要改变层次遍历的方向。
#ifndef C71_H
#define C71_H
#include<iostream>
#include<vector>
#include<queue>
using namespace std;
class TreeNode{
public:
int val;
TreeNode *left, *right;
TreeNode(int val){
this->val = val;
this->left = this->right = NULL;
}
};
class Solution {
public:
vector<vector<int>> zigzagLevelOrder(TreeNode *root) {
// write your code here
vector<vector<int>> v;
queue<TreeNode*> Q;
int j = 0;
if (root == NULL)
return v;
Q.push(root);
while (!Q.empty())
{
int size = Q.size();
vector<int> val;
for (int i = 0; i < size; ++i)
{
TreeNode* head = Q.front();
Q.pop();
val.push_back(head->val);
if (j % 2 != 0)
{
if (head->left != NULL)
Q.push(head->left);
if (head->right != NULL)
Q.push(head->right);
}
else
{
if (head->right != NULL)
Q.push(head->right);
if (head->left != NULL)
Q.push(head->left);
}
}
++j;
v.push_back(val);
}
return v;
}
};
#endif