366. Find Leaves of Binary Tree - Explanation

Problem Link

Description

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.
  • Repeat until the tree is empty.

Example 1:

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.

Example 2:

Input: root = [1]

Output: [[1]]

Constraints:

  • The number of nodes in the tree is in the range [1, 100].
  • -100 <= Node.val <= 100

Company Tags


1. DFS (Depth-First Search) with sorting

class Solution:
    def findLeaves(self, root: Optional[TreeNode]) -> List[List[int]]:
        self.pairs = []
        
        def getHeight(node):
            if node is None:
                return -1
            
            # first calculate the height of the left and right children
            leftHeight = getHeight(node.left)
            rightHeight = getHeight(node.right)
            
            # based on the height of the left and right children, obtain the height of the current (parent) node
            currHeight = max(leftHeight, rightHeight) + 1
            
            # collect the pair -> (height, val)
            self.pairs.append((currHeight, node.val))
            
            # return the height of the current node
            return currHeight
        
        getHeight(root)
        
        # sort all the (height, val) pairs
        self.pairs.sort(key=lambda p: p[0])
        
        n = len(self.pairs)
        height = 0
        i = 0
        solution = []
        
        while i < n:
            nums = []
            while i < n and self.pairs[i][0] == height:
                nums.append(self.pairs[i][1])
                i += 1
            solution.append(nums)
            height += 1
        
        return solution

Time & Space Complexity

  • Time complexity: O(NlogN)O(N \log N)
  • Space complexity: O(N)O(N)

Where NN is the total number of nodes in the binary tree


2. DFS (Depth-First Search) without sorting

class Solution:
    def findLeaves(self, root: Optional[TreeNode]) -> List[List[int]]:
        self.solution = []
        
        def getHeight(node):
            if node is None:
                return -1
            
            leftHeight = getHeight(node.left)
            rightHeight = getHeight(node.right)
            currHeight = max(leftHeight, rightHeight) + 1
            
            if len(self.solution) == currHeight:
                self.solution.append([])
            
            self.solution[currHeight].append(node.val)
            return currHeight
        
        getHeight(root)
        return self.solution

Time & Space Complexity

  • Time complexity: O(N)O(N)
  • Space complexity: O(N)O(N)

Where NN is the total number of nodes in the binary tree