Magicsheet logo

Print Binary Tree

Medium
12.5%
Updated 8/1/2025

Print Binary Tree

What is this problem about?

The Print Binary Tree problem asks you to represent a binary tree in a matrix of height h and width 2^h - 1, where the root is centered and child nodes are placed at specific positions. This coding problem calculates precise grid positions using tree height and recursive placement. The BFS, DFS, binary tree, and tree interview pattern is demonstrated through position calculation.

Why is this asked in interviews?

Meta, Amazon, and Google ask this to test understanding of binary tree structure — specifically the mathematical relationship between a node's level and its column position. The recursive position calculation is elegant and tests tree layout intuition.

Algorithmic pattern used

Recursive DFS with position calculation. Compute tree height h. Create (h+1) × (2^(h+1) - 1) matrix filled with "". Place root at (0, mid) where mid = (width-1)/2. For each node at (row, col): left child at (row+1, col - 2^(h-row-1)), right child at (row+1, col + 2^(h-row-1)). Recurse.

Example explanation

Tree: 1→(2,3). Height=2. Width = 2^3-1=7. Root at (0,3).

  • Left child 2 at (1, 3-2^(2-1-0))=(1,3-2)=(1,1).
  • Right child 3 at (1, 3+2)=(1,5). Matrix:
["","","","1","","",""]
["","2","","","","3",""]

Common mistakes candidates make

  • Incorrect width formula (2^(h+1)-1, not 2^h).
  • Off-by-one in offset calculation per level.
  • Not initializing the matrix with empty strings.
  • Computing height incorrectly (height = number of levels - 1).

Interview preparation tip

Print Binary Tree requires deriving the position formula mathematically. At level d, the left subtree width is 2^(h-d) - 1 and root is at the midpoint. Practice deriving similar tree layout formulas by working out small examples (height 1, 2, 3). Understanding the relationship between tree structure and grid coordinates is useful for visualization, debugging, and algorithm explanations in interviews.

Similar Questions