gpt4 book ai didi

javascript - Javascript 中的二叉树

转载 作者:行者123 更新时间:2023-11-29 18:30:05 24 4
gpt4 key购买 nike

我正在做这个作业:http://www.cs.colostate.edu/~anderson/ct310/index.html/doku.php?id=assignments:assignment_2

我正在用 Javascript 构建一个二叉树。基本上它是一个关系树,我们有一个接受 3 个参数的树类:数据、左子节点、右子节点。左右 child 只是存储在 var 中的新树对象。

这是树类:

function Tree( data, left, right ) 
{
// pravite data
var data = data;
var leftChild = left;
var rightChild = right;

// public functions
this.getData = function()
{
return data;
}

this.left = function()
{
return leftChild;
}

this.right = function()
{
return rightChild;
}

}

这是 toString() 方法

Tree.prototype.toString = function(indent) 
{
var spaces = '';
if (!indent)
{
indent = 0;
}
else{
spaces = spaces*indent;
}
// if the left tree isn't void
if(this.tree().left())
{
this.tree().left().toString(indent+5);
}
if(this.tree().right())
{
this.tree.right().toString(indent+5);
}
print(spaces + this.data);
}

这是我传入的数据。我们在命令行中使用 Rhino 进行测试。

var abc = new Tree('a', new Tree('b'), new Tree('c'));
abc.toString()

我在 toString 方法上遇到堆栈溢出。我的教授说在 if 语句中使用 this.Left() 因为当你递归时它会在未定义时失败。

有什么问题吗?

最佳答案

好吧,你对正确分支的最后引用缺少一些括号......

this.tree.right().toString(indent+5) // <-- right here

除此之外,我没有在任何地方看到 this.tree() 的定义。我认为所有这些地方都应该是 this.left()this.right()

此外,为了稍微优化,请考虑以下内容:

var l = this.left();
if( l) l.toString(indent+5);

这避免了额外的函数调用。

关于javascript - Javascript 中的二叉树,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9330993/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com