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.
-
For each node 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)]
.
Return the constructed matrix res.
Function Signature
def print_tree(root: list[int | None]) -> list[list[str]]:
Rules
-
The tree arrives as a level-order list.
None
marks a missing child, children of a missing node are not listed, and trailing
None
values may be omitted. For example,
[1, 2, 3, None, 4]
is a root 1 with children 2 and 3, where 2 has only a right child 4.
-
Height counts edges on the longest root-to-leaf path, so a single node has height 0.
-
Each node's cell holds its value as a decimal string, such as
"7"
or
"-12"
. Every cell without a node holds the empty string
""
.
Constraints
-
The number of nodes in the tree is between 1 and
2^10
.
-
-99 <= Node.val <= 99
-
The depth of the tree is between 1 and 10.
Examples
Input: root = [1, 2]
Output:
[
["", "1", ""],
["2", "", ""]
]
The height is 1, so the matrix is 2 x 3. The root goes to (0, 1), and its left child goes one column left of it, 2^(1-0-1) = 1, at (1, 0).
Input: root = [1, 2, 3, None, 4]
Output:
[
["", "", "", "1", "", "", ""],
["", "2", "", "", "", "3", ""],
["", "", "4", "", "", "", ""]
]
The height is 2, so the matrix is 3 x 7. The root sits at (0, 3), its children are 2 columns away at (1, 1) and (1, 5), and node 4, the right child of 2, is 1 column right of it at (2, 2).
Input: root = [1, None, -2, None, 3]
Output:
[
["", "", "", "1", "", "", ""],
["", "", "", "", "", "-2", ""],
["", "", "", "", "", "", "3"]
]
The tree is a chain of right children, so the height is 2 and the matrix is again 3 x 7. Node -2 lands at (1, 5) and node 3 at (2, 6), the last column.