Skip to content

Commit 1f1292a

Browse files
committed
Runtime: 66 ms (Top 53.29%) | Memory: 47.20 MB (Top 43.11%)
1 parent fd4609e commit 1f1292a

File tree

1 file changed

+31
-0
lines changed

1 file changed

+31
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
// Runtime: 66 ms (Top 53.29%) | Memory: 47.20 MB (Top 43.11%)
2+
3+
var widthOfBinaryTree = function(root) {
4+
if(!root) {
5+
return 0;
6+
}
7+
const q = [[root, 0]];
8+
let maxWidth = 0, l = 0, r = 0;
9+
while(q.length) {
10+
const size = q.length;
11+
const startIdx = q[0][1];
12+
for(let i = 0; i < size; ++i) {
13+
const [node, idx] = q.shift();
14+
if(i === 0) {
15+
l = idx;
16+
}
17+
if(i === size - 1) {
18+
r = idx;
19+
}
20+
const subIdx = idx - startIdx;
21+
if(node.left !== null) {
22+
q.push([node.left, 2 * subIdx + 1]);
23+
}
24+
if(node.right !== null) {
25+
q.push([node.right, 2 * subIdx + 2]);
26+
}
27+
}
28+
maxWidth = Math.max(maxWidth, r - l + 1);
29+
}
30+
return maxWidth;
31+
};

0 commit comments

Comments
 (0)