0
点赞
收藏
分享

微信扫一扫

leetcode 662 Maximum Width of Binary Tree

问题描述

给定一个二叉树,编写一个函数来获取这个树的最大宽度。树的宽度需要定义为树中任意两个叶节点之间的最大距离。这个距离是沿着从根到叶子节点路径的水平距离。

例如,给定的二叉树:

    1
/ \
3 2
/ \ \
5 3 9

最大宽度是 4 (5, 3, 9 是最宽的)。

二叉树的序列化输入是一个列表,其中空节点用 null 表示。

解法一

解题思路:

为了解决这个问题,我们可以使用层序遍历(BFS)。在遍历的过程中,我们可以记录每一层的节点数量,然后找到宽度最大的那一层。

/*
* @lc app=leetcode.cn id=662 lang=javascript
*
* [662] Maximum Width of Binary Tree
*/


// @lc code=start
function widthOfBinaryTree(root) {
if (!root) return 0;
let queue = [[root, 0]];
let maxWidth = 0;

while (queue.length) {
const levelSize = queue.length;
let left = queue[0][1];
let right = left;
for (let i = 0; i < levelSize; i++) {
const [node, pos] = queue.shift();
if (node.left) queue.push([node.left, pos * 2 + 1]);
if (node.right) queue.push([node.right, pos * 2 + 2]);
right = pos;
}
maxWidth = Math.max(maxWidth, right - left + 1);
}
return maxWidth;
}
// @lc code=end
举报

相关推荐

0 条评论