繁体   English   中英

在 Java 中删除二叉搜索树中的一个节点

[英]Deleting a node in Binary Search Tree in Java

我尝试使用这种方法以递归方式删除节点,但不知何故,它说 myRoot 将始终是 null。 你能告诉我怎么做吗?

// To delete a node from the BST
public Node deleteNode(Node myRoot, int toDel) {
    if (myRoot == null) return myRoot;
    else if (toDel < myRoot.data) myRoot.left = deleteNode(myRoot.left, toDel);
    else if (toDel > myRoot.data) myRoot.right = deleteNode(myRoot.right, toDel);
    else {
        // Leaf node
        if (myRoot.right == null && myRoot.left == null) {
            myRoot = null;
        } else if (myRoot.left == null) { // No left child
            myRoot = myRoot.right;
        } else if (myRoot.right==null){ // No right child
            myRoot = myRoot.left;
        }
    }
    return myRoot;
}

注意:- 此代码仅删除有一个子节点或没有子节点的节点。 我目前正在删除一个有 2 个孩子的节点,所以请不要为我解决这个问题。

根据对该问题的评论,您正在询问 IDE 的样式推荐,具体与以下内容相关:

 if (myRoot == null) return myRoot;

您的 IDE 意味着执行该特定return语句时, myRoot始终为null 很明显,情况确实如此,因为if确保否则return不会执行。 您的 IDE 建议您将其更改为

    if (myRoot == null) return null;

是否这样做取决于您,但就个人而言,我会根据您的 IDE 的建议 go,因为它使代码更加清晰。

暂无
暂无

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

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