【问题标题】:Insert function dosen't insert插入功能不插入
【发布时间】:2019-08-30 03:15:47
【问题描述】:

我开始以 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);
        }

    }

【问题讨论】:

  • C#C/C++ 如此不同,就你的问题而言:看看你的 InsertHelper - 它实际上从来没有 insert 数据(只是没有代码插入)

标签: c# binary-search-tree nodes


【解决方案1】:

您正在为参数指针分配一个新节点,而不是原始节点。 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为空

主要测试方法:

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


    }

【讨论】:

  • 感谢您的帮助。所以每次添加新节点都需要重新分配root?
  • @Alex 是的,如果你想使用递归。如果您仔细观察,您会发现迭代实现它更容易、更直观
  • 我进行了如上所示的编辑。看起来它仅在 BST 最初为空时才有效,但在第一次输入之后,其他的都没有添加。它显示左右为空
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多