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. windows查看文件MD5值的命令

    今天需要,就记录一下. certutil -hashfile filename MD5 certutil -hashfile filename SHA1 certutil -hashfile file ...

  2. 学习app开发思路

    1.首先在学习之前进行一次或者是整体或者是部分的检测,当第一次检测就通过,则可以认为是熟练掌握的东西(可以在后期对其进行验证是否是熟练)2.后面的学习过程,对回答的正确与否以及从第一次开始学习到目前为 ...

  3. http消息与webservice

    别人的:在一台配置较低的PC上,同时开启服务端与客户端,10000条数据,使用基于http的消息逐条进行传递,从开始传递至全部接收并处理完毕,大概需要465秒的时间:而在同一台机器上,使用WebSer ...

  4. 深入详解JVM内存模型

    JVM内存结构 由上图可以清楚的看到JVM的内存空间分为3大部分: 堆内存 方法区 栈内存 其中栈内存可以再细分为java虚拟机栈和本地方法栈,堆内存可以划分为新生代和老年代,新生代中还可以再次划分为 ...

  5. [HAOI2015]树上染色 树状背包 dp

    #4033. [HAOI2015]树上染色 Description 有一棵点数为N的树,树边有边权.给你一个在0~N之内的正整数K,你要在这棵树中选择K个点,将其染成黑色,并 将其他的N-K个点染成白 ...

  6. 【树形DP】骑士

    骑士 题目描述 \(Z\)国的骑士团是一个很有势力的组织,帮会中汇聚了来自各地的精英.他们劫富济贫,惩恶扬善,受到社会各界的赞扬. 最近发生了一件可怕的事情,邪恶的\(Y\)国发动了一场针对Z国的侵略 ...

  7. 利用vue-meta管理头部标签

    在 Vue SPA 应用中,如果想要修改HTML的头部标签,或许,你会在代码里,直接这么做 // 改下title document.title = 'what?' // 引入一段script let ...

  8. LOJ6437. 「PKUSC2018」PKUSC [计算几何]

    LOJ 思路 显然多边形旋转可以变成点旋转,不同的点的贡献可以分开计算. 然后就变成了要求一个圆在多边形内的弧长. 考虑把交点全都求出来,那么两个交点之间的状态显然是相同的,可以直接把圆弧上的中点的状 ...

  9. Spyder汉化问题

    首先感谢李增海大神,以下内容来源于http://www.lizenghai.com 必备条件 1.已安装Spyder 2.Spyder版本在3.X以上 Spyder安装: 1.anaconda下,co ...

  10. php在Linux下的相对路径问题

    如图所示,我在 /root/phpcode/ 下面有两个php文件. a.php 与 b.php,我用 a.php 去 require b.php ,然后 b.php 输出 1. 现在我在 /root ...