【发布时间】:2016-06-06 01:11:40
【问题描述】:
我正在玩一棵二叉树。我正在尝试使用递归来查找所有嵌套子项的值并将所有值推送到数组中。我从左边的树开始看它是否有效。我试图打电话给childrenArray(),但控制台说 childrenArray() 没有定义。当我询问if (typeof BinaryTree.prototype.childrenArray === 'function') 时,它返回true。请教我并告诉我为什么我无法执行我的代码?
var Tree = function(value) {
if (!(this instanceof Tree)) {
return new Tree(value);
}
this.value = value;
this.children = [];
};
Tree.prototype.addChild = function(value) {
var child = new Tree(value);
this.children.push(child);
};
Tree.prototype.contains = function(value) {
if (this.value === value) {
return true;
} else {
for (var i = 0; i < this.children.length; i++) {
if (this.children[i] && this.children[i].contains(value)) {
return true;
}
}
return false;
}
};
var BinaryTree = function(value) {
if (!(this instanceof BinaryTree)) {
return new BinaryTree(value);
}
Tree.call(this, value);
};
BinaryTree.prototype = Object.create(Tree.prototype);
BinaryTree.prototype.addChild = function(value) {
if (value < this.value) {
if (this.children[0] === undefined) {
this.children[0] = new BinaryTree(value);
}
this.children[0].addChild(value);
} else if (value > this.value) {
if (this.children[1] === undefined) {
this.children[1] = new BinaryTree(value);
}
this.children[1].addChild(value);
}
};
BinaryTree.prototype.contains = function(value) {
if (value < this.value) {
if (this.children[0] === undefined) {
return false;
}
return this.children[0].contains(value);
} else if (value > this.value) {
if (this.children[1] === undefined) {
return false;
}
return this.children[1].contains(value);
}
};
var a = new BinaryTree();
a.value = 10;
a.addChild(4);
a.addChild(11);
a.addChild(3);
BinaryTree.prototype.childrenArray = function() {
var results = [];
if (this.value) {
results.push(this.value);
}
if (this.children[0].length === 0) {
return results;
}
for (var i = 0; i < this.children[0].children.length; i++) {
if (this.children[i].value) {
results.push(this.children[i].value);
return this.childrenArray();
}
}
};
a.childrenArray();
【问题讨论】:
-
你打电话给
childArray,这似乎是未定义的。 -
您定义了
childrenArray(),但没有定义childArray()。认为您混淆了两者。 -
评论因重复而被撤销
-
嘿,我修好了,但现在问题是最大溢出。
-
您是否将
childArray替换为this.childrenArray?如果您在同一个对象上调用 childrenArray,它将开始无限递归。即便如此,好好看看你打算如何将results从一个递归级别传递到另一个级别。
标签: javascript recursion binary-tree