Reputation: 25
So I'm trying to get some practice in javascript by building up a tree class. I'm having some weird issues with a function in which I try to recursively get the leaves of the tree.
For example,
function Tree(root, branches){
this.root = root;
this.branches = branches;
}
t = new Tree(2, [new Tree(6), new Tree(5)]);
Tree.prototype.is_leaf = function(){
return !(this.branches)
}
Tree.prototype.get_leaves = function(){
mainTree = this;
root = this.root;
branches = this.branches
list_of_leaves = []
if(mainTree.is_leaf()){
list_of_leaves.push(root);
} else {
for(i = 0; i < branches.length; i++){ //go through each branch and run get_leaves
console.log(branches); //Branches logs correctly here
list_of_leaves.push.apply(list_of_leaves, branches[i].get_leaves());
/*extend the main list_of_leaves with the list of leaves of each branch (THIS LINE CAUSES THE PROBLEM)*/
console.log(branches); //Branches is set to undefined here
}
}
return list_of_leaves;
}
t.get_leaves();
When I try to run this function I get a "length of branches undefined" error. For some reason branches is getting mutated through the recursive calls, I don't understand why that is happening. Is the list_of_leaves in the array shared across all instances? So should I define get_leaves as a method within the Tree object as opposed to in it's prototype? (it seems inefficient to do this, so I was hoping there was a better way). Thanks!
Upvotes: 1
Views: 80
Reputation: 1843
For some reason you are not using var
for variable declaration, this has an effect of branches
not being a local but rather a global variable. A quick fix to your code would be to add var
to branches
like this:
function Tree(root, branches){
this.root = root;
this.branches = branches;
}
t = new Tree(2, [new Tree(6), new Tree(5)]);
Tree.prototype.is_leaf = function(){
return !(this.branches)
}
Tree.prototype.get_leaves = function(){
mainTree = this;
root = this.root;
var branches = this.branches; // <--- This line ;)
list_of_leaves = []
if(mainTree.is_leaf()){
list_of_leaves.push(root);
} else {
for(i = 0; i < branches.length; i++){ //go through each branch and run get_leaves
console.log(branches); //Branches logs correctly here
list_of_leaves.push.apply(list_of_leaves, branches[i].get_leaves());
/*extend the main list_of_leaves with the list of leaves of each branch (THIS LINE CAUSES THE PROBLEM)*/
console.log(branches); //Branches is set to undefined here
}
}
return list_of_leaves;
}
t.get_leaves();
Upvotes: 1