描述
给出一棵二叉树,返回其节点值的锯齿形层次遍历(先从左往右,下一层再从右往左,层与层之间交替进行)
您在真实的面试中是否遇到过这个题? 是
样例
给出一棵二叉树 {3,9,20,#,#,15,7}
,
3
/ \
9 20
/ \
15 7
返回其锯齿形的层次遍历为:
[
[3],
[20,9],
[15,7]
]
题目链接
程序
/**
* Definition of TreeNode:
* class TreeNode {
* public:
* int val;
* TreeNode *left, *right;
* TreeNode(int val) {
* this->val = val;
* this->left = this->right = NULL;
* }
* }
*/
class Solution {
public:
/**
* @param root: A Tree
* @return: A list of lists of integer include the zigzag level order traversal of its nodes' values.
*/
vector<vector<int>> zigzagLevelOrder(TreeNode * root) {
// write your code here
vector<vector<int>> vec;//申明一个放结果的vector
if(root==NULL){//判断是否为空
return vec;
}
bool cur=false;//判断是向左还是向右
queue<TreeNode*> que; //申明一个队列
que.push(root); //将树的根节点放入队列中
while(!que.empty()){
int count=que.size();//确定该队列的长度
vector<int> vec_temp;
while(count--){
TreeNode *temp=que.front(); //去除队列的头,并剔除
que.pop();
vec_temp.push_back(temp->val);
if(temp->left){//将该节点的所有子孩子压入队列中
que.push(temp->left);
}
if(temp->right){
que.push(temp->right);
}
}
if(cur){//反转vector
reverse(vec_temp.begin(),vec_temp.end());
}
cur=!cur;
vec.push_back(vec_temp);
}
return vec;
}
};