⚡Flashcard Drill➔
NeetCode #405LC-366MediumTreesNC Algo100
← Back to All Problems

#405 · #366 · Find Leaves of Binary Tree(寻找二叉树的叶子节点)

📌 Problem Statement & Constraints

Given the root of a binary tree, collect all its nodes level by level from the leaves upward: first all leaves are removed, then the new leaves, and so on. Return the list of levels. Constraints: the number of nodes is in [1, 100].

💡 Core Algorithmic Approaches

  1. The level of a node equals its height, where a leaf has height 0.
  2. So a single post-order traversal computing heights assigns every node to its level.
  3. Nodes at the same height are grouped together, giving exactly the removal order.
  4. This is O(n) instead of simulating the removal process repeatedly.

💻 Benchmark Python3 Implementation

class Solution:
    def findLeaves(self, root: Optional[TreeNode]) -> List[List[int]]:
        res = []

        def height(node: Optional[TreeNode]) -> int:
            """Height of the subtree: a leaf has height 0."""
            if not node:
                return -1
            h = 1 + max(height(node.left), height(node.right))
            while len(res) <= h:           # grow the level list as needed
                res.append([])
            res[h].append(node.val)
            return h

        height(root)
        return res

⚡ Complexity Deep Dive

⏱️ Time Complexity
O(n): each node is visited once.
💾 Space Complexity
O(h) for the recursion stack plus O(n) for the result.

⚠️ Interview Pitfalls & Follow-ups

  • Defining the leaf height as 1: then the levels would be off by one; a leaf must map to level 0.
  • Repeatedly simulating the removals: O(n^2).
  • Appending to res without growing it first: an IndexError when the height exceeds the current length.
  • Assuming the tree is balanced: the height can reach n for a degenerate tree.
⚡
Test muscle memory on this topic via 3-Layer Flashcards
Active Recall: Mentally formulate Prompt ➔ Math Derivation ➔ Benchmark Implementation in 3 minutes.
🎯 Drill This Card Now➔

🧩 Related Trees Problems

中文速览与面试要点

寻找二叉树的叶子节点

给你一棵二叉树的根节点 root,请按以下规则收集叶子节点:① 收集并 删除 所有叶子节点;② 重复上述操作,直到整棵树为空。返回一个二维数组,其中每一维包含每一轮收集的叶子节点(按从左到右的顺序)。约束:树中节点数目在范围 [1, 100] 内;-100 ≤ Node.val ≤ 100。

核心要点

  • 后序遍历 + 按「高度」分组(标准解) :定义叶子的高度为 0,节点的「高度」= 1 + max(左高, 右高) 。同一轮被删除的叶子恰好具有相同的高度,因此把节点按高度分组即可。
  • 为什么高度相同即同轮被删 :叶子高度为 0,删除后其父节点变成新叶子(高度 1),以此类推。
  • 实现 :递归返回节点高度,把节点值追加到 res[height] 中。
  • 复杂度 :O(n) 时间、O(h) 空间。

常见陷阱

  • 空节点高度返回 0 :会导致叶子高度为 1,索引错位。应返回 −1,使叶子高度恰好为 0。
  • 忘记 if h == len(res): res.append([]) :会越界访问。
  • 用「反复遍历删除叶子」的模拟法 :每轮 O(n)、共 O(h) 轮,总计 O(n · h),虽然 n ≤ 100 时可过,但不如高度分组法优雅。
  • 同层内顺序 :后序遍历天然保证同高度节点按「从左到右」的顺序被加入(因为先递归左子树)。

参考实现

class Solution:
    def findLeaves(self, root: 'TreeNode') -> list[list[int]]:
        res = []

        def dfs(node) -> int:
            """返回 node 的高度;叶子高度为 0。"""
            if not node:
                return -1                   # 空节点高度 -1,使叶子高度为 0
            l = dfs(node.left)
            r = dfs(node.right)
            h = 1 + max(l, r)
            if h == len(res):
                res.append([])              # 新的一轮
            res[h].append(node.val)
            return h

        dfs(root)
        return res