这个题,同样看解析,不过需要注意的是,怕数字太大,都是要在后面加个n, 具体都在下面代码中标注了
var widthOfBinaryTree = function (root) {
if (!root) {
return 0;
}
let q = [[0n, root]];
let max = 1n;
while (q.length) {
// 求每一行最大宽度
// let width = q[q.length - 1][0] - q[0][0] + 1n;
const width = q[q.length - 1][0] - q[0][0] + 1n
// 跟max对比 比max大就复制
// max = width > max ? width : max;
if (width > max) {
max = width
}
// for循环给你q的下一行增加序号和跟节点,左 序号为上一个节点的2n, 右为2n+1
let temp = []
for (const [i, node] of q) {
node.left && temp.push([i * 2n, node.left]);
node.right && temp.push([i * 2n + 1n, node.right]);
}
// 给q赋值为下一次循环做准备
q = temp;
}
return max;
};