我正在尝试在 Tree 类上编写一个 contains 函数来检查树是否包含值。尽管满足了我的停止条件(通过控制台日志验证),但该函数未返回 true。
class Tree {
constructor (value) {
this.value = value;
this.children = [];
}
addChild (tree) {
this.children.push(tree);
return true;
}
contains (value) {
if (this.value === value) {
return true;
}
if (this.children.length === 0) return false;
for (let tree of this.children) {
tree.contains(value);
}
}
}
const tree = new Tree('hello');
const subTree = new Tree('world');
console.log(tree.addChild(subTree) === true);
console.log(tree.contains('world') === true);
最佳答案
您需要从子级中返回第一个 true
查找结果,最后返回 false
作为默认值。
class Tree {
constructor (value) {
this.value = value;
this.children = [];
}
addChild (tree) {
this.children.push(tree);
return true;
}
contains (value) {
if (this.value === value) {
return true;
}
if (this.children.length === 0) return false;
for (let tree of this.children) {
if (tree.contains(value)) {
return true;
}
}
return false;
}
}
const tree = new Tree('hello');
const subTree = new Tree('world');
console.log(tree.addChild(subTree) === true);
console.log(tree.contains('world') === true);
关于javascript - 尽管满足停止条件,递归函数仍不返回,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51638463/