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

问题描述

你能告诉我为什么这段代码不会删除 BST 中的节点吗?我的代码有逻辑错误吗?

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

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

解决方法

如果有 0 个子节点,只需删除节点(Alt+8)。

如果有 1 个子节点,只需将节点替换为不为空的子节点即可。

return null