二叉树中的递归插入

时间:2015-07-02 07:00:24

标签: c# recursion tree binary-tree insertion

为什么在进行递归调用时,成员变量LEFT和RIGHT永远不会改变? 这是源代码:

public class C_Nodo

{
    int dato;
    C_Nodo left;
    C_Nodo right;

    public int DATO
    {
        get { return dato; }
        set { dato = value; }
    }

    public C_Nodo LEFT
    {
        get { return this.left; }
        set { this.left= value; }
    }

    public C_Nodo RIGHT
    {
        get { return this.right; }
        set { this.right = value; }
    }

    public C_Nodo(int inf)
    {
        this.dato = inf;
        this.left = null;
        this.right = null;
    }
}

public class C_Arbol_Bin

{   
    C_Nodo root;

    public C_Arbol_Bin()
    {
        root = null;
    }

在根目录中简单插入或进行递归调用

    public void inserta(int dat)
    {
        if (root == null)
        {
            root = new C_Nodo(dat);
        }
        else
        {
            insert_Order(this.root, dat);
        }
    }

这里我按顺序进行递归插入,具体取决于包含父节点的值,但RIGH和LEFT永远不会改变。

    public void insert_Order(C_Nodo tree, int inf)
    {
        if (tree == null)
        {
            tree = new C_Nodo(inf);
        }
        else
        {
            if (tree.DATO > inf)
            {
                insert_Order(tree.LEFT, inf);
            }
            else
            {
                insert_Order(tree.RIGHT, inf);
            }
        }
    }
}

2 个答案:

答案 0 :(得分:0)

声明像

这样的函数
public void insert_Order( ref C_Nodo tree, int inf );

此函数是函数inserta的辅助函数,因此可以声明为private

答案 1 :(得分:0)

弗拉德说的...... 基本上LEFT / RIGHT部分始终为null的原因是因为您按值传递引用类型对象,然后在其上调用 new C_Nodo() - 这将创建指向新位置的指针为你的对象。

因此,您可以使用Vlad的解决方案并通过引用传递它,或者您可以更改插入 insert_Order 方法以返回Node对象并保存它在根节点中:

    public void inserta(int dat)
    {
        if (root == null)
        {
            root = new C_Nodo(dat);
        }
        else
        {
            this.root = insert_Order(this.root, dat);
        }
    }

    private C_Nodo insert_Order(C_Nodo tree, int inf)
    {
        if (tree == null)
        {
            tree = new C_Nodo(inf);
        }
        else
        {
            if (tree.DATO > inf)
            {
                tree.LEFT = insert_Order(tree.LEFT, inf);
            }
            else
            {
                tree.RIGHT = insert_Order(tree.RIGHT, inf);
            }
        }

        return tree;
    }

有关参考文献的更多信息,请查看此文章:https://msdn.microsoft.com/en-us/library/s6938f28.aspx

相关问题