【发布时间】:2022-01-19 18:50:53
【问题描述】:
我已经开始深入研究 Tree 的主题。而且我发现了奇怪的(对我而言)行为。
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
}
}
所以,我在这里创建了一个节点结构,它获取一个整数数组,并将其分成两半,直到叶子不再包含数组的一个元素。
let n_array = [1,3,2,5];
root_node = new tree_node(n_array);
现在我想遍历树并提醒每个节点的“n_array”。 我以为应该是这样的
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;
}
}
但它不起作用。如果我使用网络浏览器控制台,那么 root.descendants.length 会给我长度。但在我的递归中,它没有。每次都是未定义
我从代码中删减了越来越多的内容,最后,我得到了这个。
function show_tree(root_node){
alert(root_node.n_array)
root_node.descendants.forEach(element => {
return show_tree(element);
});
}
有效的解决方案有效,但我不明白为什么。 我预计它会遇到错误,因为在树的末尾 root_node.descendants 将是 undefined.
更糟糕的是 - 如果在每次调用 root_node.descendants !=0 中,我不明白为什么这个递归会停止并且不会进入无限循环。 .. 请帮我理解
- 为什么我的第一个版本 show_tree 不起作用
- 为什么最后一个有效。
【问题讨论】:
-
你打错了
.length(检查拼写!!!)
标签: javascript recursion tree