Print Binary Tree - Problem
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
heightand the number of rowsmshould be equal toheight + 1. - The number of columns
nshould be equal to2^(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 atres[r+1][c-2^(height-r-1)]and its right child atres[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
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
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code