我在返回二叉树最深节点时遇到了困难。 我知道如何找到树的高度,但不知道如何返回最深节点。 以下是我的代码,我尝试循环整个树并替换传入参数的节点。 但是,我只得到了根节点作为结果。
tree.prototype.deepestnode=function()
{
if(this.root===null)
{
return 'none';
}
else
{
let node=this.root;
this.root.deepnode(1,1,node);
return node;
}
}
node.prototype.deepnode=function(maxdepth,currentdepth,node)
{
if(maxdepth<currentdepth)
{
node=this;
}
if(this.left!==null)
{
this.left.deepnode(maxdepth,++currentdepth,this.left);
}
if(this.right!==null)
{
currentdepth++;
this.right.deepnode(maxdepth,++currentdepth,this.right);
}
}
node.prototype.addnode=function(node)
{
if(node.value<this.value)
{
if(this.left===null)
{
this.left=node;
}
else
this.left.addnode(node);
}
else if(node.value>this.value)
{
if(this.right===null)
{
this.right=node;
}
else
this.right.addnode(node);
}
}
tree.prototype.addtotree=function(value)
{
let n=new node(value);
if(this.root===null)
{
this.root=n;
}
else
{
this.root.addnode(n);
}
}
addtotree()
函数的实现。 - Dimitar