gpt4 book ai didi

c# - 插入函数不插入

转载 作者:行者123 更新时间:2023-11-30 17:25:45 25 4
gpt4 key购买 nike

我以 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 已经处理了 root 为 null 的问题

主要测试方法:

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 + " ");


}

关于c# - 插入函数不插入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57720058/

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