【leetcode】Binary Tree Level Order Traversal I & II
2015-07-07 15:54
417 查看
Given a binary tree, return the level order traversal of its nodes' values. (ie, from left to right, level by level).
For example:
Given binary tree
return its level order traversal as:
分层遍历二叉树,用BFS即可
网上DFS的代码:
Binary Tree Level Order Traversal II
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:
跟上面只是顺序变了,加个reverse就行了。
For example:
Given binary tree
{3,9,20,#,#,15,7},
3 / \ 9 20 / \ 15 7
return its level order traversal as:
[ [3], [9,20], [15,7] ]
分层遍历二叉树,用BFS即可
class Solution { public: vector<vector<int>> levelOrder(TreeNode* root) { queue<TreeNode*> Q; vector<vector<int>> ans; Q.push(root); while(!Q.empty()) { int e = Q.size(); //当前层的结束位置 vector<int> partans; for(int i = 0; i < e; i++) { TreeNode * p = Q.front(); Q.pop(); if(NULL != p) { partans.push_back(p->val); Q.push(p->left); Q.push(p->right); } } if(!partans.empty()) ans.push_back(partans); } return ans; } };
网上DFS的代码:
class Solution { protected: vector<vector<int>> ans; void dfs(TreeNode *root, int height){ if (root == NULL) return; while (ans.size() <= height) ans.push_back(vector<int>()); ans[height].push_back(root->val); dfs(root->left, height + 1); dfs(root->right, height + 1); } public: vector<vector<int>> levelOrder(TreeNode* root) { dfs(root, 0); return ans; } };
Binary Tree Level Order Traversal II
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
{3,9,20,#,#,15,7},
3 / \ 9 20 / \ 15 7
return its bottom-up level order traversal as:
[ [15,7], [9,20], [3] ]
跟上面只是顺序变了,加个reverse就行了。
相关文章推荐
- java细节总结
- 打星星游戏
- 【数字图像处理之二】图像直方图均衡化
- 黑马程序员安卓Android52期 46期 35期就业班视频
- Sql Server 存储过程可选参数
- 图片展示(手动左右切换)
- springMVC注解方式+easyUI+MYSQL配置实例
- iOS8 CLLocationManager 、CLGeocoder获取地理位置
- 通过ApplicationContextAware加载Spring上下文环境
- 大整数的阶乘
- python re.search 和 re.match 正则表达式
- 密码学基础知识(五)序列密码
- 《软件学报》《计算机学报》《计算机研究与发展》为计算机类三大权威刊物
- NYOJ 198 数数
- Count Primes
- 泛型-模板函数-模板类
- PHP 获取客户端真实的ip地址
- 日历日历日历
- 对SQL连接池的理解
- PHPExcel融入ZF2