简体   繁体   English

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

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

I tried making this method which will delete the node recursively, but somehow it says that myRoot will always be null.我尝试使用这种方法以递归方式删除节点,但不知何故,它说 myRoot 将始终是 null。 Can you tell me how?你能告诉我怎么做吗?

// 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;
}

NOTE:- This code only deletes the nodes with one child or no child.注意:- 此代码仅删除有一个子节点或没有子节点的节点。 I am currently working on deleting a node with 2 children so please dont solve that for me.我目前正在删除一个有 2 个孩子的节点,所以请不要为我解决这个问题。

Per comments on the question, you are asking about a style recommendation from your IDE, related specifically to:根据对该问题的评论,您正在询问 IDE 的样式推荐,具体与以下内容相关:

 if (myRoot == null) return myRoot;

Your IDE means that when that particular return statement is executed, myRoot is always null .您的 IDE 意味着执行该特定return语句时, myRoot始终为null It is obvious that this is so, because the if ensures that otherwise, that return is not executed.很明显,情况确实如此,因为if确保否则return不会执行。 Your IDE is recommending that you change that to您的 IDE 建议您将其更改为

    if (myRoot == null) return null;

Whether you do so is up to you, but personally, I would go with your IDE's advice, because it makes the code slightly clearer.是否这样做取决于您,但就个人而言,我会根据您的 IDE 的建议 go,因为它使代码更加清晰。

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

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