2
* @param {TreeNode} root5
var printTree = function (root) {6
// find the height of the tree7
const m = getHeight(root);9
const n = 2 ** (height + 1) - 1;10
// create an empty m by n matrix12
for (let i = 0; i < m; i++) {13
ans.push(Array(n).fill(""));16
ans[0][(n - 1) / 2] = root.val.toString();17
// insert the rest of the nodes18
format(root, 0, (n - 1) / 2, ans, height);22
function getHeight(node) {24
const leftHeight = getHeight(node.left) + 1;25
const rightHeight = getHeight(node.right) + 1;26
return Math.max(leftHeight, rightHeight); // take the subtree with bigger height29
function format(node, r, c, ans, height) {30
const offset = 2 ** (height - r - 1); // calculate the common offset32
ans[r + 1][c - offset] = node.left.val.toString();33
format(node.left, r + 1, c - offset, ans, height); // recurse left node36
ans[r + 1][c + offset] = node.right.val.toString();37
format(node.right, r + 1, c + offset, ans, height); // recurse right node