简体   繁体   中英

Deleting a node in a Binary Search Tree using Java

Could you tell me why this code wont delete a node in a BST? Is there any logical error in my code?

    // To delete a node from the BST
public Node deleteNode(Node myRoot, int toDel) {
    if (myRoot == null) return null;
    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.

If 0 children, simply delete node ( return null for it).

If there is 1 child, simply replace the node with the child that is not null.

public Node deleteNode(Node myRoot, int toDel) {
    if (myRoot == null) {
      return null;
    } else if (myRoot.data == toDel) {
      if (myRoot.left != null) {
          return myRoot.left;
      } else if (myRoot.right != null) {
          return myRoot.right;
      } else {
          return null;
      }
    }
    ...
   return myRoot;
}

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.

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