首页 > 解决方案 > 如何从二叉搜索树中删除字符串

问题描述

我正在尝试从 BST 中删除一个字符串,但我无法弄清楚。我知道如何删除整数,但无法将我的代码转换为删除具有字符串的节点。这是我目前拥有的代码

    /*
     * Removes the specified string from the BST
     */

    public boolean remove(String s){
        Node ans = remove(root, s);
        if(ans == null){
            return false;
        } else {
            return true;
        }
    }

    private static Node remove(Node root, String s) {

        if (root == null)
            return null;

        if (s.compareTo(root.data) < 0) {
            root.left = remove(root.left, s);
        } else if (s.compareTo(root.data) > 0) {
            root.right = remove(root.right, s);
        } else {

            if (root.left == null) {
                return root.right;
            } else if (root.right == null)
                return root.left;

            root.data = minimum(root.right);
            root.right = remove(root.right, root.data);
        }

        return root;

    }

    public static String minimum(Node root) {
        String minimum = root.data;
        while (root.left != null) {
            minimum = root.left.data;
            root = root.left;
        }
        return minimum;
    }

标签: javabinary-treebinary-search-treeremove-method

解决方案


将所有 "Integer" 替换为 "String" 。


推荐阅读