|
| 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 | +}; |
0 commit comments