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:
height
and the number of rows m
should be equal to height + 1
.n
should be equal to 2height+1 - 1
.res[0][(n-1)/2]
).res[r][c]
, place its left child at res[r+1][c-2height-r-1]
and its right child at res[r+1][c+2height-r-1]
.""
.Return the constructed matrix res
.
Example 1:
Input: root = [1,2] Output: [["","1",""], ["2","",""]]
Example 2:
Input: root = [1,2,3,null,4] Output: [["","","","1","","",""], ["","2","","","","3",""], ["","","4","","","",""]]
Constraints:
[1, 210]
.-99 <= Node.val <= 99
[1, 10]
.This problem asks to create a formatted string matrix representation of a given binary tree. The matrix's dimensions are determined by the tree's height, and node placement follows specific rules based on their position relative to their parent.
Both solutions employ a Depth-First Search (DFS) and a Breadth-First Search (BFS) approach.
Solution 1 (DFS):
Height Calculation: A recursive helper function height(root)
calculates the tree's height. An empty tree has a height of -1; otherwise, it's 1 plus the maximum height of the left and right subtrees.
Matrix Initialization: A matrix ans
of size (height + 1) x (2height+1 - 1) is created and filled with empty strings. This pre-allocates the space needed to hold the tree representation.
Depth-First Traversal (dfs): A recursive function dfs(root, r, c)
places nodes into the matrix.
r
and column c
.c - 2<sup>height - r - 1</sup>
and the right child at c + 2<sup>height - r - 1</sup>
. This formula ensures correct spacing.Solution 2 (BFS):
Height Calculation: A BFS approach is used to calculate the height. A queue is used, traversing level by level to determine the tree's height efficiently.
Matrix Initialization: Same as in Solution 1, a matrix of appropriate dimensions is created and filled with empty strings.
Breadth-First Traversal: A queue q
is used to store tuples representing (node, row, column)
. It starts with the root node at the middle of the top row.
ans[r][c]
.Solution 1 (DFS):
Solution 2 (BFS):
Both Python solutions are provided in the original response, showing both DFS and BFS implementations. The choice between DFS and BFS depends on personal preference and the specific characteristics of the input tree. For balanced trees, the difference in performance is usually minimal. For significantly unbalanced trees, BFS might be slightly faster as the depth of the recursion in DFS might grow substantially.