【发布时间】:2019-01-12 05:04:19
【问题描述】:
我正在按正确打印节点的顺序打印出二叉树中的所有节点。但它也在列表末尾打印一个未定义的,我找不到原因。我正在为一场编程比赛而学习,如你所知,获得完美的输出很重要。它只是一个控制台的东西吗?我在控制台内置的 VS Code 和 ubuntu 终端中都试过了。代码:
function BST(value) {
this.value = value;
this.left = null;
this.right = null;
}
BST.prototype.insert = function(value) {
if( value <= this.value ){
if(this.left){
//left busy
this.left.insert(value);
}else{
//left is free
this.left = new BST(value);
}
}else{
if(this.right){
//right busy
this.right.insert(value);
}else{
//right is free
this.right = new BST(value);
}
}
}
BST.prototype.contains = function(value){
if(this.value === value){
return true;
}
if(value < this.value){
if(this.left){
return this.left.contains(value);
}else{
return false;
}
} else if(value > this.value){
if(this.right){
return this.right.contains(value);
}else{
return false;
}
}
}
BST.prototype.depthFirstTraversal = function(iteratorFunc){
if(this.left){
this.left.depthFirstTraversal(iteratorFunc);
}
if(this.value){
iteratorFunc(this.value);
}
if(this.right){
this.right.depthFirstTraversal(iteratorFunc);
}
}
var bst = new BST(50);
bst.insert(30);
bst.insert(70);
bst.insert(100);
bst.insert(60);
bst.insert(59);
bst.insert(20);
bst.insert(45);
bst.insert(35);
bst.insert(85);
bst.insert(105);
bst.insert(10);
console.log(bst.depthFirstTraversal(print));
function print(val){
console.log(val);
}
正在打印的列表是:
10
20
30
35
45
50
59
60
70
85
100
105
undefined
我得到最后一个未定义的任何原因?谢谢
【问题讨论】:
-
您的代码中似乎还有一个错误,您的树找不到 0。
if (this.value) -
我已经删除了该部分,因为它不是必需的,并对其进行了重构以支持预购、中购和后购。感谢您让我知道这个错误!
标签: javascript algorithm binary-tree