107.Binary Tree Level Order Traversal II
2015-08-02 16:00
423 查看
问题:跟上道102题基本一样,只不过是要求从最下层开始遍历。
思路:多用了一个栈,作为临时结果,最后再把栈的内容搬移到最终结果里即可。
class Solution {
public:
vector<vector<int>> levelOrderBottom(TreeNode* root) {
vector<vector<int>> res;
if(root==NULL) return res;
stack<vector<int>> tem_res;
vector<int> layer;
int cur_layer_num=0,next_layer_num=0;//当前层有多少个节点,下一层有多少个节点。每次出一个节点,当前层就减1,直到0,说明一层结束。每次进一个节点,下一层就加1,直到当前层减为0,下一层计算完毕。
queue<TreeNode*> q;
q.push(root);
cur_layer_num++;
while(!q.empty()){
TreeNode* front_node=q.front();
if(front_node->left){
q.push(front_node->left);
next_layer_num++;
}
if(front_node->right){
q.push(front_node->right);
next_layer_num++;
}
layer.push_back(front_node->val);
q.pop();
cur_layer_num--;
if(cur_layer_num==0){
tem_res.push(layer);
layer=vector<int>();
cur_layer_num=next_layer_num;
next_layer_num=0;
}
}
//反向输出
while(!tem_res.empty()){
vector<int> tem_layer=tem_res.top();
tem_res.pop();
res.push_back(tem_layer);
}
return res;
}
};
思路:多用了一个栈,作为临时结果,最后再把栈的内容搬移到最终结果里即可。
class Solution {
public:
vector<vector<int>> levelOrderBottom(TreeNode* root) {
vector<vector<int>> res;
if(root==NULL) return res;
stack<vector<int>> tem_res;
vector<int> layer;
int cur_layer_num=0,next_layer_num=0;//当前层有多少个节点,下一层有多少个节点。每次出一个节点,当前层就减1,直到0,说明一层结束。每次进一个节点,下一层就加1,直到当前层减为0,下一层计算完毕。
queue<TreeNode*> q;
q.push(root);
cur_layer_num++;
while(!q.empty()){
TreeNode* front_node=q.front();
if(front_node->left){
q.push(front_node->left);
next_layer_num++;
}
if(front_node->right){
q.push(front_node->right);
next_layer_num++;
}
layer.push_back(front_node->val);
q.pop();
cur_layer_num--;
if(cur_layer_num==0){
tem_res.push(layer);
layer=vector<int>();
cur_layer_num=next_layer_num;
next_layer_num=0;
}
}
//反向输出
while(!tem_res.empty()){
vector<int> tem_layer=tem_res.top();
tem_res.pop();
res.push_back(tem_layer);
}
return res;
}
};
相关文章推荐
- ps绘制漂亮的晶莹剔透云朵方法
- hdu 5317
- POJ-1316
- AngularJs学习笔记__1、初步了解AngularJS
- [深入理解Android卷一全文-第六章]深入理解Binder
- Remove Element
- urllib2模块
- 简单md5加密
- 全志平台linux启动流程分析
- [leetcode-45]Jump Game II(c)
- vector用法
- STL中的set容器的一点总结
- 有关collection中的一些数据结构
- uva12661 Dijkstra
- storyboard之 prepareForSegue:sender:
- leetcode 242: Valid Anagram
- android NumberPicker 数组越界的坑
- 【Angular JS】网站使用社会化评论插件,以及过程中碰到的坑
- 九度oj 1446
- ULN2003的简单使用