Problem 450350 · medium · Phase 04 Non-Linear Data Structures

Levels From the Bottom Up

binary trees · breadth-first search · queue

Given the root of a binary tree, return its levels as a list of lists, deepest level first and the root's level last. Inside each level keep the nodes in left-to-right order.

Examples

    3
   / \
  9  20
     / \
    15  7

Input:  root = build_tree([3, 9, 20, None, None, 15, 7])
Output: [[15, 7], [9, 20], [3]]
Input:  root = build_tree([])
Output: []

Constraints

  • 0 <= number of nodes <= 2000
  • -10**4 <= node.val <= 10**4
  • Target complexity: O(n) time.

Goals

  • Group nodes by level with a queue
  • Reverse the level order at the end
  • Return [] for an empty tree
Starting Python…