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
|
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); } }
|