아래의 방법을 구현하는 방법을 파악하는 데 문제가 있습니다. 깊이 우선 검색을 사용하여 트리에 값이 있는지 확인하려고하지만 구현에서 무엇이 잘못되었는지는 확실하지 않습니다. 나는이 작업을 수행 할 때최대 호출 스택 크기를 초과했습니다. 논리가 잘못된 부분을 파악할 수 없습니다.
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()'안에있는 루프 내에서'contains() '를 호출하는 것으로 추측하고 있습니다. 가난한 브라우저에서는 너무 많이됩니다. – adeneo