繁体   English   中英

在二叉树中的递归插入

[英]Recursive Insertion in a Binary Tree

为什么在进行递归调用时为什么成员变量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);
            }
        }
    }
}

像这样声明功能

public void insert_Order( ref C_Nodo tree, int inf );

另外,由于此函数是函数inserta的辅助函数,因此可以像private声明它

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

因此,您可以使用Vlad的解决方案并通过引用传递它,也可以更改insertinsert_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/zh-cn/library/s6938f28.aspx

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM