javascript - 尽管满足停止条件,递归函数仍不返回

标签 javascript

我正在尝试在 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/

相关文章:

javascript - 使用 JavaScript 将类添加到提交时的输入

javascript - 将 blob 直接上传到 s3 时出现问题

javascript - node.js - MongoDB native 中的 RegExp

javascript - 哪个按钮调用 javascript 文件

javascript - 在具有随机起始索引的数组中选择 4 个值

javascript - Laravel 和 Vue.js 使用 fetch 的 put 方法

javascript - js+html5图像处理

javascript - 使用 JavaScript setInterval() 时,JQuery datepicker 最短日期不会更改

javascript - 使用 Node.js 和 Express.js 以及 AngularJs 和 nodemailer 发送电子邮件不发送邮件

javascript - jQuery 的部分构建只是为了 $.ajax (XMLHttpRequest) 功能?