๐Ÿ“Š 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 ร— n matrix where m = height + 1 and n = 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)]
  • 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
Binary Tree โ†’ Matrix TransformationOriginal Tree12345TransformResult Matrix12345Positioning Formulaโ€ข Matrix dimensions: m = height + 1, n = 2^(height+1) - 1โ€ข Root position: [0][(n-1)/2]โ€ข Child offset: 2^(height - current_row - 1)โ€ข Left child: [row+1][col-offset], Right child: [row+1][col+offset]
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.
Asked in
Google 25 Amazon 18 Microsoft 12 Apple 8
28.5K Views
Medium Frequency
~15 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