从二叉树C#中删除

时间:2016-03-04 17:33:59

标签: c# binary-tree

嗨我在C#中从二叉树中删除时出了点问题。我不知道为什么,但这段代码不能正常工作(我的树在通话后不会改变'删除方法)。这是我的代码:

public class BinaryTree<T>
{
    public BinaryTree<T> Left, Right;
    public T Data;
    public BinaryTree()
    {
        this.Left = null;
        this.Right = null;
    }
}


public BinaryTree<T> FindNode(T value,ref BinaryTree<T> myTree)
{
    if (myTree == null) 
        return null;
    else
    {
        int result = Comparer<T>.Default.Compare(value, myTree.Data);
        if (result == 0)
            return myTree;
        else if (result > 0)
            return FindNode(value, ref myTree.Right);
        else if (result < 0)
            return FindNode(value, ref myTree.Left);
    }
    return myTree;
}

public void RemoveValue(T value,ref BinaryTree<T> myTree)
{
    BinaryTree<T> helper = new BinaryTree<T>();
    BinaryTree<T> MyTree = myTree;
    if (MyTree == null) return;
    MyTree =FindNode(value,ref MyTree);
    if (MyTree.Left == null || MyTree.Right == null)
        helper = MyTree;
    else
    {
        helper = MyTree.Left;
        while (helper.Right!=null)
            helper = helper.Right;
        MyTree.Data = helper.Data;
    }
    if (helper.Left == null)
        helper = helper.Right;
    else
        helper = helper.Left;
}

BinaryTree表示树中的每个节点。

1 个答案:

答案 0 :(得分:0)

Here is a slight clean up of you code with suggestions on how I think RemoveValue should work. I leave it up to you to finish the implementation.

public class BinaryTree<T>
{
    public T Data;
    public BinaryTree<T> Left, Right;
    public BinaryTree()
    {
        this.Left = null;
        this.Right = null;
    }

    public static BinaryTree<T> FindNode(T value, BinaryTree<T> myTree)
    {
        if (myTree == null)
            return null;
        else
        {
            int result = Comparer<T>.Default.Compare(value, myTree.Data);
            if (result == 0)
                return myTree;
            else if (result > 0)
                return FindNode(value, myTree.Right);
            else if (result < 0)
                return FindNode(value, myTree.Left);
        }
        return myTree;
    }

    public static void RemoveValue(T value, ref BinaryTree<T> myTree)
    {
        if (myTree == null)
            return;
        BinaryTree<T> treeNodeToRemove = FindNode(value, myTree);

        // First case: The node to remove has a single subtree
        if(treeNodeToRemove.Left == null ^ treeNodeToRemove.Right == null)
        {
            // We need to change the Left||Right reference of our parent to us...
        }
        // Second case: Both subtrees are null
        else if (treeNodeToRemove.Left == null && treeNodeToRemove.Right == null)
        {
            // We need to change the reference of our parent to null
        }
        // Third case: Both subtrees are full
        else
        {
            // ...
        }
    }
}

Also here is a link I used that outlines the three cases.