Print Binary Tree - Problem
๐ Binary Tree Matrix Visualization
Given the root of a binary tree, create a visually appealing string matrix that represents the tree structure. Think of it as creating a "pretty print" layout where each node is positioned perfectly to show the tree's hierarchical structure.
๐ฏ Your Mission:
- Create an
m ร nmatrix wherem = height + 1andn = 2^(height+1) - 1 - Place the root node in the center of the top row
- For each node at position
res[r][c]:- Left child goes to
res[r+1][c - 2^(height-r-1)] - Right child goes to
res[r+1][c + 2^(height-r-1)]
- Left child goes to
- Fill empty cells with empty strings
""
The result is a beautiful matrix representation that maintains the binary tree's visual structure, perfect for debugging or educational purposes!
Input & Output
example_1.py โ Simple Binary Tree
$
Input:
root = [1,2]
Tree structure:
1
/
2
โบ
Output:
[["" "1" ""],
["2" "" ""]]
๐ก Note:
Height = 1, so matrix is 2ร3. Root '1' goes to center [0][1], left child '2' goes to [1][0] using the positioning formula.
example_2.py โ Complete Binary Tree
$
Input:
root = [1,2,3,null,4]
Tree structure:
1
/ \
2 3
\
4
โบ
Output:
[["" "" "" "1" "" "" ""],
["" "2" "" "" "" "3" ""],
["" "" "4" "" "" "" ""]]
๐ก Note:
Height = 2, matrix is 3ร7. Each level uses different offset: root at [0][3], level 1 with offset 2, level 2 with offset 1.
example_3.py โ Single Node
$
Input:
root = [1]
Tree structure:
1
โบ
Output:
[["1"]]
๐ก Note:
Edge case: single node tree has height 0, resulting in a 1ร1 matrix with just the root value.
Constraints
- The number of nodes in the tree is in the range [1, 210]
- -99 โค Node.val โค 99
- The depth of the tree will be in range [0, 9]
Visualization
Tap to expand
Understanding the Visualization
1
Measure Family
Calculate tree height to determine matrix size needed
2
Find Center
Place root (grandparent) at the center of the top row
3
Position Children
Each parent's children are positioned symmetrically with calculated spacing
4
Maintain Balance
Mathematical formula ensures no overlaps and perfect visual balance
Key Takeaway
๐ฏ Key Insight: The mathematical positioning formula ensures perfect tree visualization by using exponentially decreasing spacing at each level, maintaining the binary tree's hierarchical structure in matrix form.
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code