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 ...
随机推荐
- SwipeRefreshLayout下拉刷新简单用例
自己的下拉刷新组件 下拉刷新并自动添加数据 MainActivity package com.shaoxin.myswiperefreshlayout; import android.graphics ...
- Android_AsyncTask异步任务(一)
AsyncTask,是android提供的轻量级的异步类,可以直接继承AsyncTask,在类中实现异步操作,并提供接口反馈当前异步执行的程度(可以通过接口实现UI进度更新),最后反馈执行的结果给UI ...
- acm数学(待续)
意图写出http://www.cnblogs.com/kuangbin/archive/2012/08/28/2661066.html这个东西的完善版. 1.置换,置换的运算 poj 2369 Per ...
- EF中执行sql语句,以及事务
EF to sql string sql = "select T_Task.BSID,T_Task.CloseDate,T_Task.CompleteDate,T_Task.CloseUse ...
- html的笔记
网页标准(w3c) ☞结构标准 html(骨骼)☞表现标准 CSS(美化师)☞行为标准 JavaScript(动作) 1.1 浏览器介绍 主流浏览器: ◆内核: 渲染引擎 ...
- cetnos 7 ntp服务的安装与配置
首先需要搭建yum本地仓库 http://www.cnblogs.com/jw35/p/5967677.html #搭建yum仓库方法 yum install ntp -y #安装n ...
- 了解学习JS中this的指向
[转] 首先必须要说的是,this的指向在函数定义的时候是确定不了的,只有函数执行的时候才能确定this到底指向谁,实际上this的最终指向的是那个调用它的对象(这句话有些问题,后面会解释为什么会有问 ...
- 【超级干货】手机移动端WEB资源整合
meta基础知识 H5页面窗口自动调整到设备宽度,并禁止用户缩放页面 <meta name="viewport" content="width=device-wid ...
- MySQL查询语句(select)详解(1)
1.查询记录 select*from 表名 [where 条件];eg:select*from students;//查询 students 表中所有记录,所有字段的值都显示出来select fiel ...
- IOS网络第二天 - 04-黑酷-GDataXML 解析
****** - (void)viewDidLoad { [super viewDidLoad]; /** 加载服务器最新的视频信息 */ // 1.创建URL NSURL *url = HMUrl( ...