leetcode 655. 输出二叉树 【时间击败100.00%】 【内存击败96.49%】

 1  public List<List<String>> printTree(TreeNode root) {
 2         ArrayList<List<String>> al = new ArrayList<>();
 3         if (root == null) return al;
 4         if (root.left == null && root.right == null) {
 5             al.add(new ArrayList<>());
 6             al.get(0).add(String.valueOf(root.val));
 7             return al;
 8         }
 9 
10         int high = dep(root, 1);
11         String[][] ans = new String[(int) Math.pow(2, high)][high + 1];
12         add(root, (int) Math.pow(2, high - 1), 1, (int) Math.pow(2, high - 2), ans);
13         for (int i = 1; i <= high; i++) {
14             al.add(new ArrayList<>());
15             for (int j = 1; j < ans.length; j++)
16                 al.get(i - 1).add(ans[j][i] == null ? "" : ans[j][i]);
17         }
18         return al;
19     }
20 
21     public void add(TreeNode cur, int x, int y, int diff, String[][] ans) {
22         if (cur == null) return;
23         ans[x][y] = cur.val + "";
24         add(cur.left, x - diff, y + 1, diff / 2, ans);
25         add(cur.right, x + diff, y + 1, diff / 2, ans);
26     }
27 
28 
29     public int dep(TreeNode cur, int dep) {
30         if (cur == null) return dep - 1;
31         return Math.max(dep(cur.left, dep + 1), dep(cur.right, dep + 1));
32     }
原文地址:https://www.cnblogs.com/towerbird/p/11583361.html