2 回答
TA贡献1757条经验 获得超8个赞
在循环中分配父项的父项。而是使用变量来循环父项。
class Node {
constructor(data) {
this.data = data;
this.parent = null;
this.children = [];
if (!Node.nodes) Node.nodes = [];
Node.nodes.push(this);
this.index = Node.nodes.length;
}
addChild(node) {
node.parent = this;
this.children.push(node);
}
getLevel() {
let level = 0;
let parent = this.parent; // start with parent
while (parent) { // check value
level += 1;
parent = parent.parent; // assign parent
}
//console.log('lvl',level);
return level;
}
toString() {
// console.log('lvl',this.getLevel());
let prefix = " ".repeat(this.getLevel() * 3);
prefix += this.getLevel() === 0 ? "" : "|__";
console.log(prefix + this.index);
if (this.children) {
for (let i = 0; i < this.children.length; i++) {
this.children[i].toString();
}
}
}
pathToRoot() {
return 0;
}
}
const main = (() => {
let root = new Node('root');
let kid1 = new Node('kid1');
let kid2 = new Node('kid2');
let kid3 = new Node('kid3');
let kid4 = new Node('kid4');
root.addChild(kid1);
kid1.addChild(kid2);
kid2.addChild(kid3);
kid3.addChild(kid4);
console.log('kid4 lvl :', kid4.getLevel())
root.toString(root);
console.log(root);
})();
.as-console-wrapper { max-height: 100% !important; top: 0; }
TA贡献1921条经验 获得超9个赞
这似乎与机制无关。你缺少一个基本情况(所以递归函数将永远保持运行)。您需要考虑递归应该在什么情况下结束。this
toString (){
// think of your base case here. Examples are as below
// should it be prefix === ""?
// should it be when length of prefix smaller or greater than specific length
let prefix = " ".repeat(this.getLevel()*3);
prefix += this.getLevel()===0 ? "" :"|__";
console.log(prefix + this.index);
if(this.children){
for(let i = 0; i < this.children.length; i++){
this.children[i].toString();
}
}
}
添加回答
举报