-
SLPHPython:
class Solution(object): def printTree(self, root): """ :type root: TreeNode :rtype: List[List[str]] """ self.height = self.findDepth(root) self.width = (1 << self.height) - 1 self.dmap = [[""] * self.width for x in range(self.height)] self.traverse(root, 1, self.width >> 1) return self.dmap def findDepth(self, root): if not root: return 0 return 1 + max(self.findDepth(root.left), self.findDepth(root.right)) def traverse(self, root, depth, offset): if not root: return self.dmap[depth - 1][offset] = str(root.val) gap = 1 + self.width >> depth + 1 self.traverse(root.left, depth + 1, offset - gap) self.traverse(root.right, depth + 1, offset + gap)
-
SLPHJava解法一:
public class Solution { public List<List<String>> printTree(TreeNode root) { int height = getHeight(root); String[][] res = new String[height][(1 << height) - 1]; for(String[] arr:res) Arrays.fill(arr,""); List<List<String>> ans = new ArrayList<>(); fill(res, root, 0, 0, res[0].length); for(String[] arr:res) ans.add(Arrays.asList(arr)); return ans; } public void fill(String[][] res, TreeNode root, int i, int l, int r) { if (root == null) return; res[i][(l + r) / 2] = "" + root.val; fill(res, root.left, i + 1, l, (l + r) / 2); fill(res, root.right, i + 1, (l + r + 1) / 2, r); } public int getHeight(TreeNode root) { if (root == null) return 0; return 1 + Math.max(getHeight(root.left), getHeight(root.right)); } }
-
SLPHJava解法二:
public class Solution { class Params { Params(TreeNode n, int ii, int ll, int rr) { root = n; i = ii; l = ll; r = rr; } TreeNode root; int i, l, r; } public List < List < String >> printTree(TreeNode root) { int height = getHeight(root); System.out.println(height); String[][] res = new String[height][(1 << height) - 1]; for (String[] arr: res) Arrays.fill(arr, ""); List < List < String >> ans = new ArrayList < > (); fill(res, root, 0, 0, res[0].length); for (String[] arr: res) ans.add(Arrays.asList(arr)); return ans; } public void fill(String[][] res, TreeNode root, int i, int l, int r) { Queue < Params > queue = new LinkedList(); queue.add(new Params(root, 0, 0, res[0].length)); while (!queue.isEmpty()) { Params p = queue.remove(); res[p.i][(p.l + p.r) / 2] = "" + p.root.val; if (p.root.left != null) queue.add(new Params(p.root.left, p.i + 1, p.l, (p.l + p.r) / 2)); if (p.root.right != null) queue.add(new Params(p.root.right, p.i + 1, (p.l + p.r + 1) / 2, p.r)); } } public int getHeight(TreeNode root) { Queue < TreeNode > queue = new LinkedList(); queue.add(root); int height = 0; while (!queue.isEmpty()) { height++; Queue < TreeNode > temp = new LinkedList(); while (!queue.isEmpty()) { TreeNode node = queue.remove(); if (node.left != null) temp.add(node.left); if (node.right != null) temp.add(node.right); } queue = temp; } return height; } }
-