|
| 1 | +/** |
| 2 | + * 655. Print Binary Tree |
| 3 | + * https://leetcode.com/problems/print-binary-tree/ |
| 4 | + * Difficulty: Medium |
| 5 | + * |
| 6 | + * Given the root of a binary tree, construct a 0-indexed m x n string matrix res that represents |
| 7 | + * a formatted layout of the tree. The formatted layout matrix should be constructed using the |
| 8 | + * following rules: |
| 9 | + * - The height of the tree is height and the number of rows m should be equal to height + 1. |
| 10 | + * - The number of columns n should be equal to 2height+1 - 1. |
| 11 | + * - Place the root node in the middle of the top row (more formally, at location res[0][(n-1)/2]). |
| 12 | + * - For each node that has been placed in the matrix at position res[r][c], place its left child at |
| 13 | + * res[r+1][c-2height-r-1] and its right child at res[r+1][c+2height-r-1]. |
| 14 | + * - Continue this process until all the nodes in the tree have been placed. |
| 15 | + * - Any empty cells should contain the empty string "". |
| 16 | + * |
| 17 | + * Return the constructed matrix res. |
| 18 | + */ |
| 19 | + |
| 20 | +/** |
| 21 | + * Definition for a binary tree node. |
| 22 | + * function TreeNode(val, left, right) { |
| 23 | + * this.val = (val===undefined ? 0 : val) |
| 24 | + * this.left = (left===undefined ? null : left) |
| 25 | + * this.right = (right===undefined ? null : right) |
| 26 | + * } |
| 27 | + */ |
| 28 | +/** |
| 29 | + * @param {TreeNode} root |
| 30 | + * @return {string[][]} |
| 31 | + */ |
| 32 | +var printTree = function(root) { |
| 33 | + const height = getHeight(root); |
| 34 | + const columns = Math.pow(2, height + 1) - 1; |
| 35 | + const result = new Array(height + 1).fill().map(() => { |
| 36 | + return new Array(columns).fill(''); |
| 37 | + }); |
| 38 | + |
| 39 | + fill(root, 0, Math.floor((columns - 1) / 2), height); |
| 40 | + |
| 41 | + return result; |
| 42 | + |
| 43 | + function fill(node, r, c, h) { |
| 44 | + if (!node) return; |
| 45 | + result[r][c] = node.val.toString(); |
| 46 | + fill(node.left, r + 1, c - Math.pow(2, h - r - 1), h); |
| 47 | + fill(node.right, r + 1, c + Math.pow(2, h - r - 1), h); |
| 48 | + } |
| 49 | + |
| 50 | + function getHeight(node) { |
| 51 | + if (!node) return -1; |
| 52 | + return 1 + Math.max(getHeight(node.left), getHeight(node.right)); |
| 53 | + } |
| 54 | +}; |
0 commit comments