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

Height Histogram

binary trees · postorder traversal · bottom-up aggregation

The height of a node is the number of edges on the longest path from that node down to a leaf, so every leaf has height 0. Given the root of a binary tree, return a list counts where counts[h] is the number of nodes whose height is exactly h, for h from 0 up to the height of the root. Return [] for an empty tree.

Examples

      1
     / \
    2   3
   / \   \
  4   5   6

Input:  root = build_tree([1, 2, 3, 4, 5, None, 6])
Output: [3, 2, 1]
Explanation: leaves 4, 5, 6 have height 0; nodes 2 and 3 have height 1; the root has height 2.
Input:  root = build_tree([1, None, 2, None, 3])
Output: [1, 1, 1]

Constraints

  • 0 <= number of nodes <= 2000
  • Target complexity: O(n) time.

Goals

  • Compute the height of every node from its children's heights
  • Process children before parents without recursion
  • Turn per-node results into a compact histogram
Starting Python…