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
|
function getTreeDepth(root: TreeNode | null): number { if (root === null) return 0 return 1 + Math.max(getTreeDepth(root.left), getTreeDepth(root.right)) }
function fill(root: TreeNode | null, res: string[][], depth: number, left: number, right: number) { if (root === null) return const middle = Math.floor((left + right) / 2) res[depth][middle] = "" + root.val fill(root.left, res, depth + 1, left, middle - 1) fill(root.right, res, depth + 1, middle + 1, right) }
function printTree(root: TreeNode | null): string[][] { let res: string[][] = [] if (root === null) return res const depth = getTreeDepth(root) const n = (1 << depth) - 1 res = Array.from(Array(depth), () => Array(n).fill("")) fill(root, res, 0, 0, n) return res };
|