LeetCode | 0655. 输出二叉树【Python】
2021-06-10 15:02
标签:代码 tar ini 另一个 空间 pre 二维矩阵 master bin 力扣 在一个 m*n 的二维字符串数组中输出二叉树,并遵守以下规则: 示例 1: 示例 2: 示例 3: 注意: 二叉树的高度在范围 [1, 10] 中。 DFS GitHub LeetCode | 0655. 输出二叉树【Python】 标签:代码 tar ini 另一个 空间 pre 二维矩阵 master bin 原文地址:https://www.cnblogs.com/wonz/p/14455335.html问题
输入:
1
/
2
输出:
[["", "1", ""],
["2", "", ""]]
输入:
1
/ 2 3
4
输出:
[["", "", "", "1", "", "", ""],
["", "2", "", "", "", "3", ""],
["", "", "4", "", "", "", ""]]
输入:
1
/ 2 5
/
3
/
4
输出:
[["", "", "", "", "", "", "", "1", "", "", "", "", "", "", ""]
["", "", "", "2", "", "", "", "", "", "", "", "5", "", "", ""]
["", "3", "", "", "", "", "", "", "", "", "", "", "", "", ""]
["4", "", "", "", "", "", "", "", "", "", "", "", "", "", ""]]
思路
先求出二叉树的最大深度depth, 然后构建二维矩阵,列数就是 2*depth-1,行数就是depth。
再利用 DFS 存二叉树,左右子树的节点值存到对应的 (start+end)/2 的左右侧。
代码
Python3
# 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]]:
# 求最大深度
def maxDepth(root):
if not root:
return 0
left = maxDepth(root.left)
right = maxDepth(root.right)
return 1 + max(left, right)
depth = maxDepth(root)
# 二维矩阵宽度
wid = 2**depth - 1
res = [[‘‘] * wid for _ in range(depth)]
# DFS
def dfs(root, depth, start, end):
# 当前根节点放在(start+end)/2这个中间位置
res[depth - 1][(start + end) // 2] = str(root.val)
if root.left:
dfs(root.left, depth + 1, start, (start + end) // 2)
if root.right:
dfs(root.right, depth + 1, (start + end) // 2, end)
dfs(root, 1, 0, wid)
return res
链接
文章标题:LeetCode | 0655. 输出二叉树【Python】
文章链接:http://soscw.com/essay/93187.html