# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def printTree(self, root: TreeNode) -> List[List[str]]:
depth = self.get_depth(root)
width = 2**depth -1
res = [["" for j in range(width)] for i in range(depth)]
self.fill_res(root, res, 0, width, 0)
return res
def fill_res(self, root:TreeNode, res:List[List[str]], start:int, end:int, depth_a:int):
if (root is None) or start > end:
return
mid = start + (end-start) //2
res[depth_a][mid] = str(root.val)
#print(depth_a)
self.fill_res(root.left, res, start, mid-1, depth_a+1)
self.fill_res(root.right, res, mid+1, end, depth_a+1)
def get_depth(self, root:TreeNode)-> int:
if root is None:
return 0
return max(self.get_depth(root.left), self.get_depth(root.right))+1
leetcode-655-輸出二叉樹
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.