gpt4 book ai didi

javascript - 在 es6 中查找我的树级宽度算法中的错误

转载 作者:塔克拉玛干 更新时间:2023-11-03 04:52:29 25 4
gpt4 key购买 nike

我正在练习解决算法问题,需要帮助找出我的代码中的错误。

--- 方向给定树的根节点,返回一个数组,其中每个元素都是宽度每个级别的树。

我试过在它上面运行测试用例,也在 JSBin 中运行它,但没有成功。运行测试时出现此错误:TypeError: undefined is not iterable

// my node class
class Node {
constructor(data) {
this.data = data;
this.children = [];
}

add(data) {
this.children.push(new Node(data));
}
};

function levelWidth(root) {
const store = [];
const widths = [0];
if(root){
store.push(root);
store.push('stop');
}
while(store.length > 1){
const value = store.shift();
if(value === 'stop'){
widths.push(0);
store.push(stop);
}
else {
store.push(...value.children);
widths[widths.length - 1]++;
}
}
return widths;
}

运行时

    expect(levelWidth(root)).toEqual([1, 3, 2]);

我希望获得 [1,3,2] 的数组,但却得到 TypeError: undefined is not iterable for

    store.push(...value.children);

据我所知,我正确地使用了展开运算符?

最佳答案

您当前的错误是由于 undefined variable stop 引起的;即,您的表达式 store.push(stop); 引用了一个 undefined variable stop

注释掉该行,特定错误不再是问题:

// my node class
class Node {
constructor(data) {
this.data = data;
this.children = [];
}

add (data) {
this.children.push(new Node(data));
}
};

function levelWidth (root) {
const store = [];
const widths = [0];
if (root) {
store.push(root);
store.push('stop');
}
while (store.length > 1) {
const value = store.shift();
if (value === 'stop') {
widths.push(0);
// store.push(stop);
}
else {
store.push(...value.children);
widths[widths.length - 1]++;
}
}
return widths;
}

关于javascript - 在 es6 中查找我的树级宽度算法中的错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55325660/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com