插入功能剂量不插入



我开始学习C#,背景是C/C ++。 我正在创建一个简单的 BST,但我的插入功能不起作用。任何帮助将不胜感激。

在 c/c++ 中不通过引用传递时,我会收到这种错误。 既然我创建了一个两个类 Node 和 BST,它们不应该通过引用传递吗?我在这个问题上工作了几个小时,并试图更改我的代码,但没有运气。

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);
}
}

您正在为参数指针分配一个新节点,而不是原始节点。Insert应该是:

public void Insert(int data)
{
if (root == null)
{
root = new Node(data);
}
else
{
root = InsertHelper(root, data);
}
}

InsertHelper应该是:

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;
}

事实上,你甚至不需要Insert因为InsertHelper已经处理了根为空

主要测试方法:

public static void Main()
{

BST bst = new BST();

bst.Insert(5);
bst.Insert(6);
bst.Insert(4);
bst.Insert(7);
bst.Insert(3);
Console.WriteLine(bst.Root.Data + " ");
Console.WriteLine(bst.Root.Left.Data + " ");
Console.WriteLine(bst.Root.Right.Data + " ");
Console.WriteLine(bst.Root.Left.Left.Data + " ");
Console.WriteLine(bst.Root.Right.Right.Data + " ");

}

最新更新