给出一棵二叉树,返回其节点值从底向上的层次序遍历(按从叶节点所在层到根节点所在的层遍历,然后逐层从左往右遍历)
您在真实的面试中是否遇到过这个题? Yes
样例
给出一棵二叉树 {3,9,20,#,#,15,7},
3
/ \
9 20
/ \
15 7
按照从下往上的层次遍历为:
[
[15,7],
[9,20],
[3]
]
思路:在题 二叉树的层次遍历 http://blog.csdn.net/thinkerleo1997/article/details/77370131 的基础上引入了 一个脉冲变化的‘锯齿数’,当二叉树换层数后‘锯齿数’会取相反数,这时会改变这层二叉树读入的方式
/**
* 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> > re;
if(root == NULL){
return re;
}
queue<TreeNode*> que;
que.push(root);
int should_len = 1;
int null_len = 0;
int sawtooth_num = 1; //引入 锯齿数
vector<int> now_s;
while(!que.empty()){
TreeNode *t = que.front();
que.pop();
if (t == NULL){
null_len ++;
}
else{
if(sawtooth_num == 1) //根据锯齿数来控制插入方式
{
now_s.insert(now_s.end(), t->val);
}
else
{
now_s.insert(now_s.begin(), t->val);
}
que.push(t->left);
que.push(t->right);
}
if(should_len == null_len + now_s.size()
&& now_s.size() != 0){
re.insert(re.end(), now_s);
now_s.clear();
should_len *= 2;
null_len *= 2;
sawtooth_num = -sawtooth_num; //二叉树换层后锯齿数取负数
}
}
return re;
}
};