Skip to content

Commit c724c20

Browse files
authored
Create 655-print-binary-tree.js
1 parent 544ecf0 commit c724c20

File tree

1 file changed

+29
-0
lines changed

1 file changed

+29
-0
lines changed

655-print-binary-tree.js

+29
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
/**
2+
* Definition for a binary tree node.
3+
* function TreeNode(val) {
4+
* this.val = val;
5+
* this.left = this.right = null;
6+
* }
7+
*/
8+
/**
9+
* @param {TreeNode} root
10+
* @return {string[][]}
11+
*/
12+
const printTree = function (root) {
13+
const h = getH(root)
14+
const w = Math.pow(2, h) - 1
15+
const matrix = new Array(h).fill(0).map((_) => new Array(w).fill(''))
16+
fill(root, 0, 0, w - 1)
17+
return matrix
18+
function getH(root) {
19+
if (!root) return 0
20+
return Math.max(getH(root.left), getH(root.right)) + 1
21+
}
22+
function fill(root, level, start, end) {
23+
if (!root) return
24+
let mid = (start + end) / 2
25+
matrix[level][mid] = root.val + ''
26+
fill(root.left, level + 1, start, mid - 1)
27+
fill(root.right, level + 1, mid + 1, end)
28+
}
29+
}

0 commit comments

Comments
 (0)