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. python3学习之lambda+sort

    >>> pairs = [(1, 'one'), (2, 'two'), (3, 'three'), (4, 'four')] >>> pairs.sort(key ...

  2. 《Java设计模式》之代理模式 -Java动态代理(InvocationHandler) -简单实现

    如题 代理模式是对象的结构模式.代理模式给某一个对象提供一个代理对象,并由代理对象控制对原对象的引用. 代理模式可细分为如下, 本文不做多余解释 远程代理 虚拟代理 缓冲代理 保护代理 借鉴文章 ht ...

  3. vue饿了么UI库-笔记

    1. :rules="{required: true, message: '有效期不能为空'}" :rules="{type:'date',required: true, ...

  4. GPP(Group Policy Preferences)漏洞

    再次之前先讲一些知识点: 密码的难题 每台Windows主机有一个内置的Administrator账户以及相关联的密码.大多数组织机构为了安全,可能都会要求更改密码,虽然这种方法的效果并不尽如人意.标 ...

  5. Bagging and Random Forest

    Bagging和随机森林RF. 随机森林是最受欢迎和最强大的机器学习算法之一.它是一种称为Bootstrap Aggregation或bagging的集成机器学习算法. bootstrap是一种强大的 ...

  6. 超参数(Hyperparameter)

    什么是超参数? 机器学习模型中一般有两类参数:一类需要从数据中学习和估计得到,称为模型参数(Parameter)---即模型本身的参数.比如,线性回归直线的加权系数(斜率)及其偏差项(截距)都是模型参 ...

  7. 【洛谷P5596】【XR-4】题

    solution \(y^2-x^2=ax+b\) \(y^2=x^2+ax+b\) 当\(x^2+ax+b\)为完全平方式时\(Ans=inf\) \(x \leq y\) 不妨令 \(y=x+t\ ...

  8. windows批量删除当前目录以及子目录的所有空文件夹

    在桌面创建一个记事本,将以下内容复制粘贴到记事本中,将记事本的拓展名修改为bat即可,然后将该文件放到需要执行的目录双击. @echo off setlocal enabledelayedexpans ...

  9. D3.js的v5版本入门教程(第七章)—— 比例尺的使用

    D3.js的v5版本入门教程(第七章) 比例尺在D3.js中是一个很重要的东西,我们可以这样理解d3.js中的比例尺——一种映射关系,从domain映射到range域(为什么会是domain和rang ...

  10. 【算法编程 C++ Python】字符串替换

    题目描述 请实现一个函数,将一个字符串中的空格替换成“%20”.例如,当字符串为We Are Happy.则经过替换之后的字符串为We%20Are%20Happy.   C++使用string,pyt ...