【问题标题】:Delete leaf nodes between a range in BST删除 BST 中范围之间的叶节点
【发布时间】:2021-06-10 11:43:57
【问题描述】:

我想删除叶节点,其值超出给定范围(例如 [L R])。我做了一个解决方案,我只是遍历所有节点并检查我当前叶节点的值是否在给定范围内。如果不是,那么我将删除此节点。

我的方法-

private static Node trim(Node root, int L, int R) {
    if (root == null)
        return null;

    if (root.left == null && root.right == null) {
        if (root.val < L || root.val > R)
            return null;
        else
            return root;
    }

    root.left = trim(root.left, L, R);
    root.right = trim(root.right, L, R);

    return root;
}

但这在 o(n) 中运行,因为我正在遍历所有节点(而且我没有在任何地方使用 BST 的属性)。谁能帮我找到更好/优化的解决方案?

【问题讨论】:

  • 在最坏的情况下,此算法将始终在 O(n) 中运行,因为您可能必须删除 BST 的所有叶子,并且其中可能有 O(n)。所以当涉及到最坏的情况时,你的算法已经是最优的了。为了在实践中获得更好的结果,您可以使用 BST 属性停止探索分支。请尝试相应地编辑此问题,您非常接近解决方案。

标签: java algorithm binary-search-tree tree-traversal


【解决方案1】:

就像 m.raynal 说的那样,既然你只想移除叶子,你就不会比 O(n) 更好。

只有当分支中的所有节点都在范围内时,您才能添加快捷方式,例如

private static Node trim(Node root, int L, int R) {

    return trim(root, L, R, null,null);
}

private static Node trim(Node root, int L, int R, Integer lBound, Integer rBound)
{
    if (root == null)
        return null;

    if (lBound != null && lBound >= L && rBound != null && rBound <= R ) {
        return root;
    }
    
    if (root.left == null && root.right == null) {
        if (root.val < L || root.val > R)
            return null;
        else
            return root;
    }

    root.left = trim(root.left, L, R, lBound , root.val);
    root.right = trim(root.right, L, R, root.val, rBound );

    return root;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-01-16
    • 1970-01-01
    • 2021-04-06
    • 1970-01-01
    • 2014-05-26
    • 2016-11-11
    相关资源
    最近更新 更多