Skip to content
Problem 655 · LeetCode 655(opens in a new tab)

Print Binary Tree

MediumBreadth-first search

You are given the root of a binary tree whose height (the number of edges on the longest path from the root down) is h. Draw it into a grid of strings with h + 1 rows and 2ʰ⁺¹ − 1 columns, with rows and columns counted from 0.

The root goes in the middle column of row 0. If a node sits at row r and column c, its left child goes at row r + 1, column c − 2^(h − r − 1), and its right child at row r + 1, column c + 2^(h − r − 1). Each node’s cell holds its value as a string; every other cell holds the empty string "". Return the grid.

Example 1

Input:  root = [3, 9, 4, null, null, 7]
Output: [["", "", "", "3", "", "", ""],
         ["", "9", "", "", "", "4", ""],
         ["", "", "", "", "7", "", ""]]
Why:    h = 2, so 3 rows of 7; children sit 2 columns out, then 1
2 more examples and the constraints

Example 2

Input:  root = [8]
Output: [["8"]]
Why:    h = 0 gives a single cell

Example 3

Input:  root = [-4, null, 6]
Output: [["", "-4", ""],
         ["", "", "6"]]
Why:    h = 1; 6 is one column right of the root

Constraints

  • 1 ≤ number of nodes ≤ 1,024
  • −99 ≤ Node.val ≤ 99
  • The tree has at most 10 levels (h ≤ 9)

Your turn first

Have a go on paper or in your own editor, then reveal the approaches from the simplest up.

Try it on LeetCode(opens in a new tab)
  1. Recursion on column rangesO(h·2ʰ)
  2. BFS with column offsetsO(h·2ʰ)

The idea in one sentence

The pattern, how to spot it, and the best complexity.

Side by side

ApproachTimeCells written for a 10-level treeVerdict
Recursion on column rangesO(h·2ʰ)
Passes; recursive
BFS with column offsetsO(h·2ʰ)
Best; direct formula, no ranges

h = height in edges. Both are bound by the output grid of (h + 1)·(2ʰ⁺¹ − 1) cells.

Edge cases to test

  • One node. h = 0, so the grid is a single cell holding the value.
  • A chain. Ten nodes in a line give a 10 × 1,023 grid that is almost all empty strings.
  • Negative values. Write "-4", not "4"; convert the whole number to a string.
  • Last row. Nodes on row h have no children, so the offset is never used there; avoid a negative exponent.

Common mistakes

  • Measuring the height in nodes instead of edges, which doubles the width.
  • Using the root’s offset on every row instead of halving it each row down.
  • Filling the grid with spaces or nulls instead of empty strings.

How to talk through it

  1. 1Clarify. Is height counted in edges? Do empty cells hold ""?
  2. 2Size the grid. One pass for h, then h + 1 rows and 2ʰ⁺¹ − 1 columns.
  3. 3Explain the halving. Each node owns a block of columns and sits in its middle, so the child offset halves per row.
  4. 4Code a BFS. Queue (node, row, column), write, queue children at ∓ offset.
  5. 5Test out loud. Try one node and a node with only a right child.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?