Given the root of a binary tree, construct a 0-indexed m x n string matrix res that represents a formatted layout of the tree.

The formatted layout matrix should be constructed using the following rules:

  • The height of the tree is height and the number of rows m should be equal to height + 1.
  • The number of columns n should be equal to 2^(height+1) - 1.
  • Place the root node in the middle of the top row (more formally, at location res[0][(n-1)/2]).
  • For each node that has been placed in the matrix at position res[r][c], place its left child at res[r+1][c-2^(height-r-1)] and its right child at res[r+1][c+2^(height-r-1)].
  • Continue this process until all the nodes in the tree have been placed.
  • Any empty cells should contain the empty string "".

Return the constructed matrix res.

Input & Output

Example 1 — Basic Tree
$ Input: root = [1,2,3,null,4]
Output: [["","","","1","","",""],["","2","","","","3",""],["","","4","","","",""]]
💡 Note: Tree height is 2, so matrix is 3×7. Root 1 goes at center (0,3). Node 2 at (1,1), node 3 at (1,5), node 4 at (2,2).
Example 2 — Single Node
$ Input: root = [1]
Output: [["1"]]
💡 Note: Single node tree has height 0, creating 1×1 matrix with just the root node.
Example 3 — Larger Tree
$ Input: root = [1,2,3,4,5,6,7]
Output: [["","","","1","","",""],["","2","","","","3",""],["","4","","5","","6","7"]]
💡 Note: Complete binary tree with height 2. Each level uses power-of-2 spacing: level 0 spacing=4, level 1 spacing=2, level 2 spacing=1.

Constraints

  • The number of nodes in the tree is in the range [1, 210]
  • 0 ≤ Node.val ≤ 109

Visualization

Tap to expand
Binary Tree to Matrix TransformationInput Tree1234Position CalculationHeight = 2, Matrix = 3×7Root: (0,3) - centerLevel 1: ±2^(2-1) = ±2Node 2: (1,1), Node 3: (1,5)Level 2: ±2^(2-2) = ±1Node 4: (2,2)Output Matrix["","","","1","","",""]["","2","","","","3",""]["","","4","","","",""]Tree nodes positioned using power-of-2 spacing formulaEach level has half the spacing of the level above
Understanding the Visualization
1
Input Tree
Binary tree [1,2,3,null,4] with nodes at different levels
2
Calculate Positions
Use height and level to determine exact matrix positions
3
Matrix Output
3×7 matrix with nodes placed at calculated positions, empty strings elsewhere
Key Takeaway
🎯 Key Insight: Use the formula 2^(height-row-1) to calculate exact column positions, ensuring proper tree spacing in the matrix
Asked in
Facebook 25 Amazon 18 Microsoft 15
34.5K Views
Medium Frequency
~25 min Avg. Time
847 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen