简体   繁体   English

使用 Java 删除二叉搜索树中的节点

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

Could you tell me why this code wont delete a node in a BST?你能告诉我为什么这段代码不会删除 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.我目前正在删除一个有 2 个孩子的节点,所以请不要为我解决这个问题。

If 0 children, simply delete node ( return null for it).如果有 0 个子节点,只需删除节点( return null )。

If there is 1 child, simply replace the node with the child that is not null.如果有 1 个子节点,只需将节点替换为不是 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;
}

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

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