二叉搜索树删除方法

时间:2015-02-06 13:41:22

标签: java recursion binary-search-tree

我正在制作一个按字符串键排序的二叉搜索树。每个节点由与密钥相关联的无序链接信息列表组成。树是有序的(按字母顺序排列)。

我已经完成了大部分程序,但是在删除方法时遇到了问题。

基本上它必须是递归的。该方法必须删除具有给定密钥的节点,以便如果" Architecture"是给定的字符串,我必须遍历树并删除相应的节点" Architecture"作为关键。

我遇到了麻烦,因为我必须删除一个字符串。其他任务使用整数,我必须删除最高或最低值。但是,我不是删除具有最高或最低String值的节点,而是删除等于指定String的节点。

所有我要问的是如何使用这种方法。如果你选择不这样做,你就不必提供任何实际的代码,但是一些指示或建议会很好。

谢谢。

//My attempt:
//Removes node with corresponding k
public void remove(String k) {
    rootNode = remove(rootNode, k);
}

//Recursive method:
private KeyNode remove(KeyNode x, String k) {
    if (x == null) {
        return x;
    }
    //int comparison with compareTo
    //if less than 0, left node = remove(left node, k)
    //if greater than 0, right node = remove(right node, k)
    //if left node and right node are both null, return null
    //if left node is null, return left node
    //if right node is null, return right node
    //return
}

1 个答案:

答案 0 :(得分:0)

你可以做这样的事情

public rootNode remove (String k, rootNode n) {
    if (n == null)
        return null;

    if (k.compareTo(n.key)<0)
        remove (k, n.leftChild);
    else if (k.compareTo(n.key)>0)
        remove (k, n.rightChild);
    else {
        if (n.leftChild != null && n.rightChild != null)    {
            /* n has two children, find max from left then 
             * switch it with n and remove n */

        }
        else if(n.leftChild != null) {
            /* n has a left child only then left child replaces n 
             * and n is deleted */


        }
        else if(n.rightChild != null) {
            /* n has a right child only then right child replaces n
             * and n is deleted*/

        }
        else {
            n = null;
        }
    }

}