LC.P655[输出二叉树]

方法一:DFS

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
45
46
47
48
/**
* 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 {
List<List<String>> ans;
int height;

public List<List<String>> printTree(TreeNode root) {
getHeight(root, 0);
int m = height + 1, n = (1 << height + 1) - 1;
ans = new ArrayList<>();
for (int i = 0; i < m; ++i) {
List<String> list = new ArrayList<>();
for (int j = 0; j < n; ++j) {
list.add("");
}
ans.add(list);
}
dfs(root, 0, (n - 1) >> 1);
return ans;
}

private void dfs(TreeNode root, int r, int c) {
if (root == null) return;
ans.get(r).set(c, String.valueOf(root.val));
dfs(root.left, r + 1, c - (1 << height - r - 1));
dfs(root.right, r + 1, c + (1 << height - r - 1));
}

private void getHeight(TreeNode root, int depth) {
if (root == null) return;
height = Math.max(height, depth);
getHeight(root.left, depth + 1);
getHeight(root.right, depth + 1);
}
}
  • 时间复杂度:$O(nm)$
  • 空间复杂度:$O(nm)$