C# 二叉树中的递归插入
为什么在我进行递归调用时,成员变量LEFT和RIGHT从不改变? 以下是源代码:C# 二叉树中的递归插入,c#,recursion,tree,binary-tree,insertion,C#,Recursion,Tree,Binary Tree,Insertion,为什么在我进行递归调用时,成员变量LEFT和RIGHT从不改变? 以下是源代码: public class C_Nodo { int dato; C_Nodo left; C_Nodo right; public int DATO { get { return dato; } set { dato = value; } } public C_Nodo LEFT { get { r
public class C_Nodo
{
int dato;
C_Nodo left;
C_Nodo right;
public int DATO
{
get { return dato; }
set { dato = value; }
}
public C_Nodo LEFT
{
get { return this.left; }
set { this.left= value; }
}
public C_Nodo RIGHT
{
get { return this.right; }
set { this.right = value; }
}
public C_Nodo(int inf)
{
this.dato = inf;
this.left = null;
this.right = null;
}
}
public class C_Arbol_Bin
{
C_Nodo root;
public C_Arbol_Bin()
{
root = null;
}
在根目录中简单插入或进行递归调用
public void inserta(int dat)
{
if (root == null)
{
root = new C_Nodo(dat);
}
else
{
insert_Order(this.root, dat);
}
}
这里,我根据包含父节点的值按顺序进行递归插入,但RIGH和LEFT永远不会更改
public void insert_Order(C_Nodo tree, int inf)
{
if (tree == null)
{
tree = new C_Nodo(inf);
}
else
{
if (tree.DATO > inf)
{
insert_Order(tree.LEFT, inf);
}
else
{
insert_Order(tree.RIGHT, inf);
}
}
}
}
将函数声明为
public void insert_Order( ref C_Nodo tree, int inf );
另外,由于该函数是函数inserta的一个辅助函数,因此它可以像Vlad所说的那样声明为私有函数。。。
基本上,左/右部分始终为空的原因是,您通过值传递引用类型对象,然后对其调用new C_Nodo()——这将为对象创建一个指向新位置的指针
因此,您可以使用Vlad的解决方案并通过引用传递它,也可以更改插入和插入顺序方法以返回节点对象并将其保存在根节点中:
public void inserta(int dat)
{
if (root == null)
{
root = new C_Nodo(dat);
}
else
{
this.root = insert_Order(this.root, dat);
}
}
private C_Nodo insert_Order(C_Nodo tree, int inf)
{
if (tree == null)
{
tree = new C_Nodo(inf);
}
else
{
if (tree.DATO > inf)
{
tree.LEFT = insert_Order(tree.LEFT, inf);
}
else
{
tree.RIGHT = insert_Order(tree.RIGHT, inf);
}
}
return tree;
}
查看这篇文章,了解更多关于参考文献的信息:它看起来像
C
,说C#
…什么???这就是defniitley C#,看看get和set值。不管怎样,你的递归调用是什么?放置断点,并告诉我们树实际上包含什么。