I tried making this method which will delete the node recursively, but somehow it says that myRoot will always be 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.
Per comments on the question, you are asking about a style recommendation from your IDE, related specifically to:
if (myRoot == null) return myRoot;
Your IDE means that when that particular return
statement is executed, myRoot
is always null
. It is obvious that this is so, because the if
ensures that otherwise, that return
is not executed. Your IDE is recommending that you change that to
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.