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 找二叉树的叶节点的更多相关文章

  1. [LeetCode] Find Leaves of Binary Tree 找二叉树的叶节点

    Given a binary tree, find all leaves and then remove those leaves. Then repeat the previous steps un ...

  2. [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 ...

  3. LeetCode 366. Find Leaves of Binary Tree

    原题链接在这里:https://leetcode.com/problems/find-leaves-of-binary-tree/#/description 题目: Given a binary tr ...

  4. 【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 ...

  5. 【LeetCode】366. Find Leaves of Binary Tree 解题报告 (C++)

    作者: 负雪明烛 id: fuxuemingzhu 个人博客:http://fuxuemingzhu.cn/ 目录 题目描述 题目大意 解题方法 DFS 日期 题目地址:https://leetcod ...

  6. 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 ...

  7. 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 ...

  8. 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 ...

  9. 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 ...

随机推荐

  1. 下载恶意pcap包的网站汇总

    说几个我经常用的,免费的:1.  Malware  Traffic  Analysis:  http://www.malware-traffic-analysis.net/2018/index.htm ...

  2. 攻击链路识别——CAPEC(共享攻击模式的公共标准)、MAEC(恶意软件行为特征)和ATT&CK(APT攻击链路上的子场景非常细)

    结合知识图谱对网络威胁建模分析,并兼容MITRE组织的CAPEC(共享攻击模式的公共标准).MAEC和ATT&CK(APT攻击链路上的子场景非常细)等模型的接入,并从情报中提取关键信息对知识图 ...

  3. VS2012 VS2010 VTK引入设置

    1.C/C++ ---> 附加包含的目录 F:/VTK61/VTK-6.1.0/SLN/Filters/Sources F:/VTK61/VTK-6.1.0/VTK-6.1.0/Filters/ ...

  4. 做阉割版Salesforce难成伟大的TOB企业

    https://www.lieyunwang.com/archives/446227 猎云注:当前中国市场环境下,有没有可能诞生一批SaaS级企业服务公司?东方富海合伙人陈利伟用三个方面基础性问题解答 ...

  5. 2019牛客多校第九场AThe power of Fibonacci——扩展BM

    题意 求斐波那契数列m次方的前n项和,模数为 $1e9$. 分析 线性递推乘线性递推仍是线性递推,所以上BM. 由于模数非质数,上扩展版的BM. 递推多少项呢?本地输入发现最大为与前57项有关(而且好 ...

  6. LeetCode 841. Keys and Rooms

    原题链接在这里:https://leetcode.com/problems/keys-and-rooms/ 题目: There are N rooms and you start in room 0. ...

  7. rhcsa备战笔记

    笔记全部手打 转载请加原文链接 0)重置密码开机按e 找到linux16行 rd.break console=tty0  ctrl+xmount -o remount,rw /sysrootchroo ...

  8. 【转载】Visual Studio(VS) F12 查看DLL源代码

    https://www.cnblogs.com/zhaoqingqing/p/6751757.html esharper官网:https://www.jetbrains.com/resharper/ ...

  9. BZOJ 3166: [Heoi2013]Alo 链表+可持久化trie

    链表这个东西非常好用啊 ~ code: #include <bits/stdc++.h> #define N 50010 #define inf 2000400000 #define se ...

  10. 46、Spark SQL工作原理剖析以及性能优化

    一.工作原理剖析 1.图解 二.性能优化 1.设置Shuffle过程中的并行度:spark.sql.shuffle.partitions(SQLContext.setConf()) 2.在Hive数据 ...