I've started to dig into the Tree's theme. And I've found strange (for me) behaviour.
class tree_node {
constructor(n_array) {
this.n_array = n_array;
this.descendants = [];
this.child();
}
child() {
if (this.n_array.length !=1){
let m = Math.floor(this.n_array.length / 2);
let l = this.n_array.slice(0,m);
let r = this.n_array.slice(m);
const left = new tree_node(l);
const right = new tree_node(r);
this.descendants.push(left, right);
}
else return 0
}
}
So, here I've created a node structure, which gets an integer array, and splits it in half till leaves will not contain only one element of the array.
let n_array = [1,3,2,5];
root_node = new tree_node(n_array);
Now I want to walk through the tree and alert the "n_array" of every node. I've supposed that it should be like this
function show_tree(root_node){
if (root_node.descendants.lenght != 0){
root_node.descendants.forEach(element => {
return show_tree(element);
});
}
else {
alert(root_node.n_array)
return 0;
}
}
But it doesn't work. If I use a web browser console then root.descendants.length gives me the length. But in my recursion, it doesn't. Every time it's undefined
I've cut more and more from the code and finally, I've got this.
function show_tree(root_node){
alert(root_node.n_array)
root_node.descendants.forEach(element => {
return show_tree(element);
});
}
The working solution works, but I don't understand why. I expect that it will run into an error, because at the end of the tree root_node.descendants will be undefined.
And what's even worse - I don't understand why this recursion stops and does not go into an endless loop if in every call root_node.descendants !=0 ... Please help me to understand
- Why my first version of show_tree doesn't work
- Why the last one is working.
.length(check spelling!!!)