Binary Tree Level Order Traversal II
2016-07-21 20:40
274 查看
Given a binary tree, return the bottom-up level order traversal of its nodes' values. (ie, from left to right, level by level from leaf to root).
For example:
Given binary tree
return its bottom-up level order traversal as:
Subscribe to see which companies asked this question
把上个的结果逆序就可以;
/**
* 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>> levelOrderBottom(TreeNode* root) {
vector<vector<int>>res;
if(root == NULL) return res;
queue<TreeNode*>q;
q.push(root);
while(!q.empty()){
vector<int>p;
int _size = q.size();
for(int i = 0; i < _size; i++){
TreeNode *temp = q.front();
q.pop();
p.push_back(temp->val);
if(temp->left)
q.push(temp->left);
if(temp->right)
q.push(temp->right);
}
res.push_back(p);
}
reverse(res.begin(), res.end());
return res;
}
};
For example:
Given binary tree
[3,9,20,null,null,15,7],
3 / \ 9 20 / \ 15 7
return its bottom-up level order traversal as:
[ [15,7], [9,20], [3] ]
Subscribe to see which companies asked this question
把上个的结果逆序就可以;
/**
* 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>> levelOrderBottom(TreeNode* root) {
vector<vector<int>>res;
if(root == NULL) return res;
queue<TreeNode*>q;
q.push(root);
while(!q.empty()){
vector<int>p;
int _size = q.size();
for(int i = 0; i < _size; i++){
TreeNode *temp = q.front();
q.pop();
p.push_back(temp->val);
if(temp->left)
q.push(temp->left);
if(temp->right)
q.push(temp->right);
}
res.push_back(p);
}
reverse(res.begin(), res.end());
return res;
}
};
相关文章推荐
- java 关于对“是否可以从一个static方法内部发出对非static方法的调用”问题的理解
- XML基础阶段小结
- js实现的对象深拷贝
- c++ learning note
- 第十一讲:存储虚拟化(一)
- The Text Splitting【贪心】
- php 性能分析工具xhprof使用简介
- [6]访问控制权限 0X01(隐藏具体实现)
- 【Redis系列】Redis的事务处理
- mysql 错误代码:1118解决方法
- linux下的redis配置外网问题
- 字符串搜索之KMP算法(伪代码)
- 偿还技术债 - 通过重构拯救老代码
- RxJava / RxAndroid
- Binary Tree Level Order Traversal
- 【CodeForces】612B - HDD is Outdated Technology(思维)
- linux环境变量及权限的理解
- 程序员入门必读:编程语言争霸 霸主是他
- POJ - 1088 滑雪(DP/记忆化搜索)
- 13A - Numbers