I'm printing out all the nodes in a binary tree in order which is printing the nodes correctly. But it's also printing an undefined at the end of the list and I can't find the reason why. I'm studying for a programming contest and It's important to get a perfect output as you already know. Is it just a console thing? I tried it both in VS Code built in console and in the ubuntu terminal. The code:
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);
}
The list being printed is:
10
20
30
35
45
50
59
60
70
85
100
105
undefined
Any reason why I'm getting that last undefined?. Thanks
You don't need to log the result of depthFirstTraversal
because it doesn't return anything (or rather, it returns undefined
). To avoid logging that undefined
value just change:
console.log(bst.depthFirstTraversal(print));
to
bst.depthFirstTraversal(print);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.