CodePark/ problems / Tree Values Row by Row
START PRACTICINGPRACTICE
Coding problem · Data structures and algorithms › Trees: depth-first and breadth-first

Tree Values Row by Row

mediumabout 20 minutes in an interview

Given the root of a binary tree, return its values row by row, from the top row down. Each row is an array of values, read from left to right.

  • Return an array of arrays. result[0] holds the root, result[1] holds the root's children, and so on.
  • An empty tree returns [].
  • Values may be negative or repeated.
  • The tree has up to 150,000 nodes.
Input: root = [3, 9, 20, null, null, 15, 7] Output: [[3], [9, 20], [15, 7]]
Input: root = [1, 2, null, 3] Output: [[1], [2], [3]]
Input: root = [] Output: []