[LeetCode] 366. Find Leaves of Binary Tree 找二叉树的叶节点
Given a binary tree, find all leaves and then remove those leaves. Then repeat the previous steps until the tree is empty.
Example:
Given binary tree
1
/ \
2 3
/ \
4 5
Returns [4, 5, 3], [2], [1].
Explanation:
1. Remove the leaves [4, 5, 3] from the tree
1
/
2
2. Remove the leaf [2] from the tree
1
3. Remove the leaf [1] from the tree
[]
Returns [4, 5, 3], [2], [1].
Credits:
Special thanks to @elmirap for adding this problem and creating all test cases.
给一个二叉树,找出它的叶节点然后删除,重复此步骤,直到二叉树为空。
The key to solve this problem is converting the problem to be finding the index of the element in the result list. Then this is a typical DFS problem on trees.
Java:
public List<List<Integer>> findLeaves(TreeNode root) {
List<List<Integer>> result = new ArrayList<List<Integer>>();
helper(result, root);
return result;
}
// traverse the tree bottom-up recursively
private int helper(List<List<Integer>> list, TreeNode root){
if(root==null)
return -1;
int left = helper(list, root.left);
int right = helper(list, root.right);
int curr = Math.max(left, right)+1;
// the first time this code is reached is when curr==0,
//since the tree is bottom-up processed.
if(list.size()<=curr){
list.add(new ArrayList<Integer>());
}
list.get(curr).add(root.val);
return curr;
}
Python:
class Solution(object):
def findLeaves(self, root):
"""
:type root: TreeNode
:rtype: List[List[int]]
"""
def findLeavesHelper(node, result):
if not node:
return -1
level = 1 + max(findLeavesHelper(node.left, result), \
findLeavesHelper(node.right, result))
if len(result) < level + 1:
result.append([])
result[level].append(node.val)
return level result = []
findLeavesHelper(root, result)
return result
C++:
// Time: O(n)
// Space: O(h) /**
* 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>> findLeaves(TreeNode* root) {
vector<vector<int>> result;
findLeavesHelper(root, &result);
return result;
} private:
int findLeavesHelper(TreeNode *node, vector<vector<int>> *result) {
if (node == nullptr) {
return -1;
}
const int level = 1 + max(findLeavesHelper(node->left, result),
findLeavesHelper(node->right, result));
if (result->size() < level + 1){
result->emplace_back();
}
(*result)[level].emplace_back(node->val);
return level;
}
};
类似题目:
[LeetCode] 104. Maximum Depth of Binary Tree 二叉树的最大深度
[LeetCode] 310. Minimum Height Trees 最小高度树
[LeetCode] 545. Boundary of Binary Tree 二叉树的边界
All LeetCode Questions List 题目汇总
[LeetCode] 366. 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, collect a tree's nodes as if you were doing this: Collect and remove all leaves ...
- LeetCode 366. Find Leaves of Binary Tree
原题链接在这里:https://leetcode.com/problems/find-leaves-of-binary-tree/#/description 题目: Given a binary tr ...
- 【leetcode】366.Find Leaves of Binary Tree
原题 Given a binary tree, collect a tree's nodes as if you were doing this: Collect and remove all lea ...
- 【LeetCode】366. Find Leaves of Binary Tree 解题报告 (C++)
作者: 负雪明烛 id: fuxuemingzhu 个人博客:http://fuxuemingzhu.cn/ 目录 题目描述 题目大意 解题方法 DFS 日期 题目地址:https://leetcod ...
- 366. 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 ...
- 366. Find Leaves of Binary Tree C#
Example:Given binary tree 1 / \ 2 3 / \ 4 5 Returns [4, 5, 3], [2], [1]. Explanation: 1. Removing th ...
- 366. Find Leaves of Binary Tree输出层数相同的叶子节点
[抄题]: Given a binary tree, collect a tree's nodes as if you were doing this: Collect and remove all ...
- LeetCode 111. Minimum Depth of Binary Tree (二叉树最小的深度)
Given a binary tree, find its minimum depth. The minimum depth is the number of nodes along the shor ...
随机推荐
- UVA-439, Knight Moves(深度优先搜索)
#include<iostream> #include<queue> #include<cstring> #include<string> #inclu ...
- [转]kafka要等一段时间才能消费到数据
kafka要等一段时间才能消费到数据 pythonkafka 为什么用python写的kafka客户端脚本,程序一运行就能生产数据,而要等一段时间才能消费到数据(topic里面有数据).(pyk ...
- 使用selenium谷歌浏览器驱动配置:
from selenium import webdriver#导入谷歌浏览器的chrome_driverchrome_driver = r"C:\python36\Lib\site-pack ...
- java 修改HttpServletRequest的参数或请求头
场景:过滤器中获取参数Token并添加到请求头(用户认证兼容老系统) 请求头和请求参数是不能直接修改,也没有提供修改的方法,但是可以在过滤器和拦截器中使用HttpServletRequestWrapp ...
- php解决大文件断点续传
核心原理: 该项目核心就是文件分块上传.前后端要高度配合,需要双方约定好一些数据,才能完成大文件分块,我们在项目中要重点解决的以下问题. * 如何分片: * 如何合成一个文件: * 中断了从哪个分片开 ...
- JS变量和变量交换的三种方法
一.what 变量就是用来存储数据的容器 二.how 通过var 关键字定义一个变量 var n1; //定义变量 变量的赋值:通过赋值运算符“=” 给变量赋值. var n2=123; //定义变量 ...
- 利用 PHP CURL zip压缩文件上传
$postData['file'] = "@".getcwd()."/../attachment/qianbao/{$customer_id}.zip"; $t ...
- [bzoj1008] 越狱
Description 监狱有连续编号为1...N的N个房间,每个房间关押一个犯人,有M种宗教,每个犯人可能信仰其中一种.如果相邻房间的犯人的宗教相同,就可能发生越狱,求有多少种状态可能发生越狱 数据 ...
- 指针的运算符&、*
int y=0; int* yptr=&y; •互相反作用 •*&yptr -> * (&yptr) -> * (yptr的地址)-> 得到那个地址上的变量 ...
- mysql 字符类以及重复元字符
字符类 [:alnum:]=[a-zA-Z0-] [:alpha:]=[a-zA-Z] [:digit:]=[-] [:lower:]=[a-z] [:upper:]=[A-Z] [:xdigit:] ...