LeetCode 题解工作台

输出二叉树

给你一棵二叉树的根节点 root ,请你构造一个下标从 0 开始、大小为 m x n 的字符串矩阵 res ,用以表示树的 格式化布局 。构造此格式化布局矩阵需要遵循以下规则: 树的 高度 为 height ,矩阵的行数 m 应该等于 height + 1 。 矩阵的列数 n 应该等于 2 heig…

category

4

题型

code_blocks

6

代码语言

hub

3

相关题

当前训练重点

中等 · 二分·树·traversal

bolt

答案摘要

先通过 `DFS` 求二叉树的高度 (高度从 `0` 开始),然后根据 求得结果列表的行数 和列数 。 根据 , 初始化结果列表 `ans`,然后 `DFS` 遍历二叉树,依次在每个位置填入二叉树节点值(字符串形式)即可。

Interview AiBox logo

Interview AiBox 实时 AI 助手,陪你讲清 二分·树·traversal 题型思路

试试 AiBox 面试助手arrow_forward
description

题目描述

给你一棵二叉树的根节点 root ,请你构造一个下标从 0 开始、大小为 m x n 的字符串矩阵 res ,用以表示树的 格式化布局 。构造此格式化布局矩阵需要遵循以下规则:

  • 树的 高度height ,矩阵的行数 m 应该等于 height + 1
  • 矩阵的列数 n 应该等于 2height+1 - 1
  • 根节点 需要放置在 顶行正中间 ,对应位置为 res[0][(n-1)/2]
  • 对于放置在矩阵中的每个节点,设对应位置为 res[r][c] ,将其左子节点放置在 res[r+1][c-2height-r-1] ,右子节点放置在 res[r+1][c+2height-r-1]
  • 继续这一过程,直到树中的所有节点都妥善放置。
  • 任意空单元格都应该包含空字符串 ""

返回构造得到的矩阵 res

 

 

示例 1:

输入:root = [1,2]
输出:
[["","1",""],
 ["2","",""]]

示例 2:

输入:root = [1,2,3,null,4]
输出:
[["","","","1","","",""],
 ["","2","","","","3",""],
 ["","","4","","","",""]]

 

提示:

  • 树中节点数在范围 [1, 210]
  • -99 <= Node.val <= 99
  • 树的深度在范围 [1, 10]
lightbulb

解题思路

方法一:两次 DFS

先通过 DFS 求二叉树的高度 hh(高度从 0 开始),然后根据 hh 求得结果列表的行数 mm 和列数 nn

根据 mm, nn 初始化结果列表 ans,然后 DFS 遍历二叉树,依次在每个位置填入二叉树节点值(字符串形式)即可。

时间复杂度 O(h×2h)O(h\times 2^h),空间复杂度 O(h)O(h)。其中 hh 是二叉树的高度。忽略结果返回值的空间消耗。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
    def printTree(self, root: Optional[TreeNode]) -> List[List[str]]:
        def height(root):
            if root is None:
                return -1
            return 1 + max(height(root.left), height(root.right))

        def dfs(root, r, c):
            if root is None:
                return
            ans[r][c] = str(root.val)
            dfs(root.left, r + 1, c - 2 ** (h - r - 1))
            dfs(root.right, r + 1, c + 2 ** (h - r - 1))

        h = height(root)
        m, n = h + 1, 2 ** (h + 1) - 1
        ans = [[""] * n for _ in range(m)]
        dfs(root, 0, (n - 1) // 2)
        return ans
speed

复杂度分析

指标
时间complexity is O(n) for traversing all n nodes of the tree. Space complexity is O(n) for storing the resulting matrix and O(h) for the recursion stack, where h is the tree height.
空间Depends on the final approach
psychology

面试官常问的追问

外企场景
  • question_mark

    They may emphasize correct node placement for symmetric visualization.

  • question_mark

    Expect discussion of DFS versus BFS for position calculation.

  • question_mark

    Watch for questions about handling null children and empty cells.

warning

常见陷阱

外企场景
  • error

    Miscalculating column mid-points causing misaligned nodes.

  • error

    Not initializing the matrix to correct dimensions before filling values.

  • error

    Confusing depth and height, leading to incorrect row or column counts.

swap_horiz

进阶变体

外企场景
  • arrow_right_alt

    Output tree nodes level by level but preserve relative horizontal spacing for symmetry.

  • arrow_right_alt

    Print only the left or right subtree matrix while maintaining column alignment.

  • arrow_right_alt

    Adapt to non-binary trees, adjusting column calculation for multiple children per node.

help

常见问题

外企场景

输出二叉树题解:二分·树·traversal | LeetCode #655 中等