C# 插入函数dosen';t插入
我以C/C++为背景开始学习C。我正在创建一个简单的BST,但我的插入函数无法工作。任何帮助都将不胜感激 在c/c++中,如果不通过引用传递,就会出现这种错误。既然我创建了两个类节点和BST,它们不应该通过引用传递吗?我在这个问题上花了几个小时,试图修改代码,但没有成功C# 插入函数dosen';t插入,c#,binary-search-tree,nodes,C#,Binary Search Tree,Nodes,我以C/C++为背景开始学习C。我正在创建一个简单的BST,但我的插入函数无法工作。任何帮助都将不胜感激 在c/c++中,如果不通过引用传递,就会出现这种错误。既然我创建了两个类节点和BST,它们不应该通过引用传递吗?我在这个问题上花了几个小时,试图修改代码,但没有成功 public Node(int data) { this.data = data; this.right = null; this.left = null;
public Node(int data)
{
this.data = data;
this.right = null;
this.left = null;
}
public Node Left
{
get { return left; }
set { left = value; }
}
public Node Right
{
get { return right; }
set { right = value; }
}
public int Data
{
get { return data; }
set { data = value; }
}
}
class BST
{
private Node root;
public BST()
{
root = null;
}
public Node Root
{
get { return root; }
set { root = value; }
}
public void Insert(int data)
{
if (root == null)
{
root = new Node(data);
}
else
{
InsertHelper(root, data);
}
}
public void InsertHelper( Node root, int data)
{
if (root == null)
{
root = new Node(data);
//return root;
}
if (root.Data > data)
{
InsertHelper(root.Left, data);
}
if (root.Data < data)
{
InsertHelper(root.Right, data);
}
}
公共节点(int数据)
{
这个数据=数据;
this.right=null;
this.left=null;
}
左公共节点
{
获取{return left;}
设置{left=value;}
}
公共节点权限
{
获取{return right;}
设置{right=value;}
}
公共整数数据
{
获取{返回数据;}
设置{data=value;}
}
}
BST级
{
私有节点根;
公共BST()
{
root=null;
}
公共节点根
{
获取{返回根;}
设置{root=value;}
}
公共空白插入(整型数据)
{
if(root==null)
{
根=新节点(数据);
}
其他的
{
InsertHelper(根,数据);
}
}
公共void InsertHelper(节点根,int数据)
{
if(root==null)
{
根=新节点(数据);
//返回根;
}
如果(root.Data>Data)
{
InsertHelper(root.Left,数据);
}
if(root.Data
您正在为参数指针分配一个新节点,而不是原来的节点。Insert
应该是:
public void Insert(int data)
{
if (root == null)
{
root = new Node(data);
}
else
{
root = InsertHelper(root, data);
}
}
public Node InsertHelper( Node root, int data)
{
if (root == null)
return new Node(data);
if (root.Data > data)
{
root.Left = InsertHelper(root.Left, data);
}
if (root.Data < data)
{
root.Right = InsertHelper(root.Right, data);
}
return root;
}
和InsertHelper
应为:
public void Insert(int data)
{
if (root == null)
{
root = new Node(data);
}
else
{
root = InsertHelper(root, data);
}
}
public Node InsertHelper( Node root, int data)
{
if (root == null)
return new Node(data);
if (root.Data > data)
{
root.Left = InsertHelper(root.Left, data);
}
if (root.Data < data)
{
root.Right = InsertHelper(root.Right, data);
}
return root;
}
C#
与C/C++
有很大的不同,正如你的问题:看看你的插入器帮助者
-它实际上从不插入数据(只是没有插入的代码)非常感谢您的帮助。所以每次添加新节点时,我们都需要重新分配根节点?@Alex是的,如果您想使用递归。如果仔细观察,您会发现迭代实现它更容易、更直观。我进行了如上所示的编辑。看起来它只在BST最初为空时起作用,但在第一次输入后e其他未添加。它显示左侧和右侧为空