Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
Skip to content

Commit 32d55d9

Browse files
committed
Add solution #662
1 parent 1fcc7d9 commit 32d55d9

File tree

2 files changed

+53
-0
lines changed

2 files changed

+53
-0
lines changed

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

Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,52 @@
1+
/**
2+
* 662. Maximum Width of Binary Tree
3+
* https://leetcode.com/problems/maximum-width-of-binary-tree/
4+
* Difficulty: Medium
5+
*
6+
* Given the root of a binary tree, return the maximum width of the given tree.
7+
*
8+
* The maximum width of a tree is the maximum width among all levels.
9+
*
10+
* The width of one level is defined as the length between the end-nodes (the leftmost and
11+
* rightmost non-null nodes), where the null nodes between the end-nodes that would be present
12+
* in a complete binary tree extending down to that level are also counted into the length
13+
* calculation.
14+
*
15+
* It is guaranteed that the answer will in the range of a 32-bit signed integer.
16+
*/
17+
18+
/**
19+
* Definition for a binary tree node.
20+
* function TreeNode(val, left, right) {
21+
* this.val = (val===undefined ? 0 : val)
22+
* this.left = (left===undefined ? null : left)
23+
* this.right = (right===undefined ? null : right)
24+
* }
25+
*/
26+
/**
27+
* @param {TreeNode} root
28+
* @return {number}
29+
*/
30+
var widthOfBinaryTree = function(root) {
31+
const queue = [[root, 0n]];
32+
let result = 0n;
33+
34+
while (queue.length) {
35+
const total = queue.length;
36+
const levelStart = queue[0][1];
37+
let levelEnd;
38+
39+
for (let i = 0; i < total; i++) {
40+
const [node, index] = queue.shift();
41+
levelEnd = index;
42+
if (node.left) queue.push([node.left, index * 2n]);
43+
if (node.right) queue.push([node.right, index * 2n + 1n]);
44+
}
45+
46+
result = result > (levelEnd - levelStart + 1n)
47+
? result
48+
: (levelEnd - levelStart + 1n);
49+
}
50+
51+
return Number(result);
52+
};

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -498,6 +498,7 @@
498498
658|[Find K Closest Elements](./0658-find-k-closest-elements.js)|Medium|
499499
659|[Split Array into Consecutive Subsequences](./0659-split-array-into-consecutive-subsequences.js)|Medium|
500500
661|[Image Smoother](./0661-image-smoother.js)|Easy|
501+
662|[Maximum Width of Binary Tree](./0662-maximum-width-of-binary-tree.js)|Medium|
501502
680|[Valid Palindrome II](./0680-valid-palindrome-ii.js)|Easy|
502503
684|[Redundant Connection](./0684-redundant-connection.js)|Medium|
503504
686|[Repeated String Match](./0686-repeated-string-match.js)|Easy|

0 commit comments

Comments
 (0)