深度优先遍历二叉树

655.输出二叉树

难度中等198收藏分享切换为英文接收动态反馈

给你一棵二叉树的根节点 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:

img

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

示例 2:

img

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

提示:

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

题解

直接通过深度优先遍历获取树的高度,然后创建一个(m, n)的二维字符串list,之后递归的遍历树,并将对应结点的值放在该二维字符串list数组中

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
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
int h, m, n;
List<List<String>> ans;
public List<List<String>> printTree(TreeNode root) {
dfs1(root, 0);
m = h + 1; n = (1 << (h + 1)) - 1;
ans = new ArrayList<>();
for (int i = 0; i < m; i++) {
List<String> cur = new ArrayList<>();
for (int j = 0; j < n; j++) cur.add("");
ans.add(cur);
}
dfs2(root, 0, (n - 1) / 2);
return ans;
}
void dfs1(TreeNode root, int depth) {
if (root == null) return ;
h = Math.max(h, depth);
dfs1(root.left, depth + 1);
dfs1(root.right, depth + 1);
}
void dfs2(TreeNode root, int x, int y) {
if (root == null) return ;
ans.get(x).set(y, String.valueOf(root.val));
dfs2(root.left, x + 1, y - (1 << (h - x - 1)));
dfs2(root.right, x + 1, y + (1 << (h - x - 1)));
}
}

  • 时间复杂度:$O(n \times m)$
  • 空间复杂度:$O(n \times m)$

image-20220823020900603


655.输出二叉树
http://example.com/2022/08/23/leetcode每日一题/655.输出二叉树/
作者
madao33
发布于
August 23, 2022
许可协议