Binary Tree Level Order Traversal II问题及解法
来源:互联网 发布:怎么免费注册淘宝网店 编辑:程序博客网 时间:2024/06/06 05:38
问题描述:
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).
示例:
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]]
问题分析:
要获取每一层的结点信息,首推树的层次遍历BFS。每遍历一层,就可以将它存储到数组中。
过程详见代码:
/** * 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,tq; q.push(root); tq.push(root); while(!tq.empty()) { vector<int> v; while(!q.empty()) { TreeNode* node = q.front(); v.push_back(node->val); if(node->left != NULL) tq.push(node->left); if(node->right != NULL) tq.push(node->right); tq.pop(); q.pop();}res.insert(res.begin(),v);q = tq;} return res; }};
代码不难理解~~~
0 0
- Binary Tree Level Order Traversal II问题及解法
- Binary Tree Level Order Traversal问题及解法
- Binary Tree Zigzag Level Order Traversal问题及解法
- LeetCode: Binary Tree Level Order Traversal II
- [LeetCode]Binary Tree Level Order Traversal II
- LeetCode Binary Tree Level Order Traversal II
- [Leetcode] Binary Tree Level Order Traversal II
- Binary Tree Level Order Traversal II
- Binary Tree Level Order Traversal II
- LeetCode Binary Tree Level Order Traversal II
- [LeetCode] Binary Tree Level Order Traversal II
- Binary Tree Level Order Traversal II
- Binary Tree Level Order Traversal II
- Binary Tree Level Order Traversal II
- 【leetcode】Binary Tree Level Order Traversal II
- [LeetCode]Binary Tree Level Order Traversal II
- Binary Tree Level Order Traversal II
- Binary Tree Level Order Traversal II
- BZOJ3809: Gty的二逼妹子序列
- tomcat server.xml中文版
- RabbitMQ消息队列(五):Routing 消息路由[转]
- 算法笔记_071-SPFA算法简单介绍(Java)
- 自定义倒计时控件
- Binary Tree Level Order Traversal II问题及解法
- RecyclerView中解决item点击持久变色问题
- 深度学习开源框架选型准则和知名框架调研(一)
- ACM(贪心系列)
- 炫酷的水滴ViewPagerIndicator
- 169. Majority Element
- printf格式标志
- OrzOrzOrz
- Oracle sys和system用户、sysdba 和sysoper系统权限、sysdba和dba角色的区别