Skip to content

Commit 389d696

Browse files
authored
Create 662-maximum-width-of-binary-tree.js
1 parent 2f54d7c commit 389d696

File tree

1 file changed

+31
-0
lines changed

1 file changed

+31
-0
lines changed

662-maximum-width-of-binary-tree.js

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
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 {number}
11+
*/
12+
const widthOfBinaryTree = function(root) {
13+
const mins = [0]
14+
let max = 0
15+
16+
dfs(root, 0, 0)
17+
return max
18+
19+
// depth first search
20+
function dfs(currentNode, depth, position) {
21+
if (!currentNode) return
22+
if (depth === mins.length) {
23+
mins[depth] = position
24+
}
25+
26+
const delta = position - mins[depth]
27+
max = Math.max(max, delta + 1)
28+
dfs(currentNode.left, depth + 1, delta * 2)
29+
dfs(currentNode.right, depth + 1, delta * 2 + 1)
30+
}
31+
}

0 commit comments

Comments
 (0)