下記のメソッドの実装方法を理解するのに問題があります。ツリーに値が含まれているかどうかを調べるために深さの最初の検索を使用しようとしていますが、私の実装に何が問題なのかよく分かりません。私はこれを行うとき最大コールスタックサイズを超えました。ロジックが間違っている箇所を特定できない
class Tree {
constructor(val) {
this.value = val;
this.children = [];
}
addChild(val) {
this.children.push(new Tree(val));
}
contains(val) {
if (this.value === val) {
return true;
} else if (this.children.length > 0) {
for (var i = 0; i < this.children.length; i++) {
this.contains(this.children[i].contains(value));
}
// When it gets to the leaf node, how do I go back to the previous call?
// Do I need to return something here?
}
return false; // I may be incorrect on this, but it should return false (execute this line) only when every node has been visited, and there are no more nodes to check.
}
};
だから:
const T = new Tree(100);
T.addChild(50);
T.addChild(40);
T.children[0].addChild(3);
console.log(T.contains(40));
は私があるため、最大コールスタックエラーのうちエラー。
実際に 'contains()'の中にあるループの中で 'contains()'を2回呼び出すと推測していますが、貧弱なブラウザではあまりにも多くなります – adeneo