Leetcode: Find Leaves of Binary Tree
Given a binary tree, collect a tree's nodes as if you were doing this: Collect and remove all leaves, repeat until the tree is empty. Example:
Given binary tree
1
/ \
2 3
/ \
4 5
Returns [4, 5, 3], [2], [1]. Explanation:
1. Removing the leaves [4, 5, 3] would result in this tree: 1
/
2
2. Now removing the leaf [2] would result in this tree: 1
3. Now removing the leaf [1] would result in the empty tree: []
Returns [4, 5, 3], [2], [1].
Better Solution: https://discuss.leetcode.com/topic/49194/10-lines-simple-java-solution-using-recursion-with-explanation/2
For this question we need to take bottom-up approach. The key is to find the height of each node. The height of a node is the number of edges from the node to the deepest leaf.
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public List<List<Integer>> findLeaves(TreeNode root) {
List<List<Integer>> res = new ArrayList<>();
helper(root, res);
return res;
} public int helper(TreeNode cur, List<List<Integer>> res) {
if (cur == null) return -1;
int level = 1 + Math.max(helper(cur.left, res), helper(cur.right, res));
if (res.size() <= level)
res.add(new ArrayList<Integer>());
res.get(level).add(cur.val);
cur.left = cur.right = null;
return level;
}
}
First time solution: HashSet+ DFS
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public List<List<Integer>> findLeaves(TreeNode root) {
ArrayList<List<Integer>> res = new ArrayList<List<Integer>>();
if (root == null) return res;
HashSet<TreeNode> visited = new HashSet<>();
while (!visited.contains(root)) {
ArrayList<Integer> leaves = new ArrayList<Integer>();
helper(root, leaves, visited);
res.add(new ArrayList<Integer>(leaves));
}
return res;
} public void helper(TreeNode cur, ArrayList<Integer> leaves, HashSet<TreeNode> visited) {
if ((cur.left==null || visited.contains(cur.left)) && (cur.right==null || visited.contains(cur.right))) {
leaves.add(cur.val);
visited.add(cur);
return;
}
if (cur.left!=null && !visited.contains(cur.left))
helper(cur.left, leaves, visited);
if (cur.right!=null && !visited.contains(cur.right))
helper(cur.right, leaves, visited);
}
}
Leetcode: Find Leaves of Binary Tree的更多相关文章
- [LeetCode] Find Leaves of Binary Tree 找二叉树的叶节点
Given a binary tree, find all leaves and then remove those leaves. Then repeat the previous steps un ...
- [LeetCode] 366. Find Leaves of Binary Tree 找二叉树的叶节点
Given a binary tree, find all leaves and then remove those leaves. Then repeat the previous steps un ...
- Leetcode 笔记 110 - Balanced Binary Tree
题目链接:Balanced Binary Tree | LeetCode OJ Given a binary tree, determine if it is height-balanced. For ...
- [LeetCode] Serialize and Deserialize Binary Tree 二叉树的序列化和去序列化
Serialization is the process of converting a data structure or object into a sequence of bits so tha ...
- LeetCode:Minimum Depth of Binary Tree,Maximum Depth of Binary Tree
LeetCode:Minimum Depth of Binary Tree Given a binary tree, find its minimum depth. The minimum depth ...
- [LeetCode] Serialize and Deserialize Binary Tree
Serialize and Deserialize Binary Tree Serialization is the process of converting a data structure or ...
- LeetCode——Serialize and Deserialize Binary Tree
Description: Serialization is the process of converting a data structure or object into a sequence o ...
- 【一天一道LeetCode】#106. Construct Binary Tree from Inorder and Postorder Traversall
一天一道LeetCode 本系列文章已全部上传至我的github,地址:ZeeCoder's Github 欢迎大家关注我的新浪微博,我的新浪微博 欢迎转载,转载请注明出处 (一)题目 来源:http ...
- LeetCode——Maximum Depth of Binary Tree
LeetCode--Maximum Depth of Binary Tree Question Given a binary tree, find its maximum depth. The max ...
随机推荐
- caffe中权值初始化方法
首先说明:在caffe/include/caffe中的 filer.hpp文件中有它的源文件,如果想看,可以看看哦,反正我是不想看,代码细节吧,现在不想知道太多,有个宏观的idea就可以啦,如果想看代 ...
- Python for Informatics 第11章 正则表达式五(译)
注:文章原文为Dr. Charles Severance 的 <Python for Informatics>.文中代码用3.4版改写,并在本机测试通过. 11.4 转义字符 之前我们在正 ...
- Hello cnblog!
Test Markdown #!/usr/env/python # coding: utf-8 # 这是一个测试文件 print "hahah" def t(): print &q ...
- Masonry小结
一,容易混淆的问题 1.make.left.equal(xxx)的参数若为某个控件,则默认为以该控件的 left 为基准对照. //these two constraints are exactly ...
- thinkphp pathinfo nginx 无法加载模块:Index
thinkphp 报了 无法加载模块:Index 错误位置 FILE: /var/multrix/wxactivity_archive/ThinkPHP/Library/Think/Dispatche ...
- Mybatis拦截器 mysql load data local 内存流处理
Mybatis 拦截器不做解释了,用过的基本都知道,这里用load data local主要是应对大批量数据的处理,提高性能,也支持事务回滚,且不影响其他的DML操作,当然这个操作不要涉及到当前所lo ...
- ios 单例设计模式
单例模式的意思就是只有一个实例.单例模式确保某一个类只有一个实例,而且自行实例化并向整个系统提供这个实例.这个类称为单例类.单例可用性非常高,用于登录用户管理等可供全局调用. + (AccountMa ...
- BSBuDeJie_03
一 快速登录 1 改变状态栏的style - (UIStatusBarStyle)preferredStatusBarStyle { return UIStatusBarStyleLightConte ...
- C++ 画星号图形——空心矩形(核心代码记录)
int mi=(int)a; int mj=(int)b; ;i<mi;i++) { ;j<mj;j++) { ||i==mi-) cout<<"*"; | ...
- 将f2fs文件系统到磁盘
1· 用git下载f2fs文件系统tools的源代码.下载地址如下:http://git.kernel.org/cgit/linux/kernel/git/jaegeuk/f2fs-tools.g ...