Maximum Width of Binary Tree LeetCode solution in JavaScript

1
/**
2
* Definition for a binary tree node.
3
* function TreeNode(val, left, right) {
4
* this.val = (val===undefined ? 0 : val)
5
* this.left = (left===undefined ? null : left)
6
* this.right = (right===undefined ? null : right)
7
* }
8
*/
9
/**
10
* @param {TreeNode} root
11
* @return {number}
12
*/
13
var widthOfBinaryTree = function (root) {
14
if (!root) return 0;
15

16
let res = 0,
17
row = [[root, 0]];
18
while (row.length > 0) {
19
const nextRow = [];
20
let curStart = -1,
21
curEnd = -2;
22
for (let i = 0; i < row.length; i++) {
23
const [node, index] = row[i];
24
if (curStart === -1) {
25
curStart = index;
26
}
27

28
curEnd = index;
29

30
if (node.left) {
31
nextRow.push([node.left, index * 2]);
32
}
33

34
if (node.right) {
35
nextRow.push([node.right, index * 2 + 1]);
36
}
37
}
38

39
res = Math.max(res, curEnd - curStart + 1);
40
if (nextRow.length === 1) {
41
nextRow[0][1] = 0;
42
}
43
row = nextRow;
44
}
45

46
return res;
47
};

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0