插入功能不插入

时间:2019-08-30 03:15:47

标签: c# binary-search-tree nodes

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

    }

1 个答案:

答案 0 :(得分: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 + " ");


    }
相关问题