| 考点 | 难度 |
|---|---|
| DFS | Medium |
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 2height+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 at res[r+1][c-2height-r-1] and its right child at res[r+1][c+2height-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.
先算height和width
每一个node的left child在下一行到起点的一半,right child在下一行终点的一半。
class Solution(object):
def printTree(self, root):
def get_height(node):
return 0 if not node else 1 + max(get_height(node.left), get_height(node.right))
def update_output(node, row, left, right):
if not node:
return
mid = int((left + right) / 2)
self.output[row][mid] = str(node.val)
update_output(node.left, row + 1 , left, mid - 1)
update_output(node.right, row + 1 , mid + 1, right)
height = get_height(root)
width = 2 ** height - 1
self.output = [[''] * width for i in range(height)]
update_output(node=root, row=0, left=0, right=width - 1)
return self.output