Find Leaves of Binary Tree — LeetCode 366 Python Solution

MediumLeetCode PremiumTreeDepth-First SearchBinary Tree
Problem
#366
Reading time
4 min

The problem

Given the root of a binary tree, collect a tree's nodes as if you were doing this: Collect all the leaf nodes. Remove all the leaf nodes.

Example

Input
root = [1,2,3,4,5]
Output
[[4,5,3],[2],[1]]
Explanation
[[3,5,4],[2],[1]] and [[3,4,5],[2],[1]] are also considered correct answers since per each level it does not matter the order on which elements are returned.

Python solution

Python
# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
    def findLeaves(self, root: Optional[TreeNode]) -> List[List[int]]:
        def dfs(root: Optional[TreeNode]) -> int:
            if root is None:
                return 0
            l, r = dfs(root.left), dfs(root.right)
            h = max(l, r)
            if len(ans) == h:
                ans.append([])
            ans[h].append(root.val)
            return h + 1

        ans = []
        dfs(root)
        return ans

Complexity

MeasureComplexity
TimeO(V+E)
SpaceO(V) auxiliary

Pattern: Tree Traversal

Choose the order — preorder, inorder, postorder, level — and the problem solves itself. LeetCode 366. Find Leaves of Binary Tree is filed here because LeetCode tags it Tree and Binary Tree, which is the vocabulary this hub collects.

The tree traversal guide has the Python template for the pattern and the 225 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 366. Find Leaves of Binary Tree?
LeetCode 366. Find Leaves of Binary Tree is rated Medium on LeetCode.
What is the time complexity of LeetCode 366. Find Leaves of Binary Tree?
The Python solution on this page runs in O(V+E).
What is the space complexity of LeetCode 366. Find Leaves of Binary Tree?
The Python solution on this page uses O(V) auxiliary space.
What topics does LeetCode 366. Find Leaves of Binary Tree cover?
LeetCode 366. Find Leaves of Binary Tree is tagged Tree, Depth-First Search and Binary Tree on LeetCode.
Is LeetCode 366. Find Leaves of Binary Tree a premium problem?
Yes. LeetCode 366. Find Leaves of Binary Tree is a LeetCode Premium problem, so the full statement and test cases require a paid LeetCode subscription.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview