655. 输出二叉树
题目描述
代码实现
# 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]]:
# 设树高h, 则内层列表元素个数为2**h - 1
def get_depth(root):
if not root:
return 0
return 1 + max(get_depth(root.left), get_depth(root.right))
depth = get_depth(root)
# res = [[""] * (2**depth - 1)]* depth ### 注意不能使用这一句,因为外层列表是复制引用,参考https://www.cnblogs.com/molinchn/p/14090035.html
res = [[''] * (2**depth - 1) for _ in range(depth)]
def pre_order(root, level=0, low=0, high=2**depth - 1 -1): # 2**depth - 1是每一层元素个数,2**depth - 1 -1是最后一个位置下标
if not root:
return
mid = low + (high - low) // 2
res[level][mid] = str(root.val)
pre_order(root.left, level + 1, low, mid - 1)
pre_order(root.right, level + 1, mid + 1, high)
pre_order(root)
return res
参考
https://leetcode-cn.com/problems/print-binary-tree/solution/655-shu-chu-er-cha-shu-by-jue-qiang-zha-zha/