力扣 450. 删除二叉搜索树中的节点

题目

给定一个二叉搜索树的根节点 root 和一个值 key,删除二叉搜索树中的 key 对应的节点,并保证二叉搜索树的性质不变。返回二叉搜索树(有可能被更新)的根节点的引用。

一般来说,删除节点可分为两个步骤:
首先找到需要删除的节点;
如果找到了,删除它。
说明: 要求算法时间复杂度为 O(h),h 为树的高度。

示例

root = [5,3,6,2,4,null,7]
key = 3

5

/
3 6
/ \
2 4 7

给定需要删除的节点值是 3,所以我们首先找到 3 这个节点,然后删除它。

一个正确的答案是 [5,4,6,2,null,null,7], 如下图所示。

5

/
4 6
/
2 7

另一个正确答案是 [5,2,6,null,4,null,7]。

5

/
2 6
\
4 7

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/delete-node-in-a-bst
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

方法1:模拟

BST的删除操作~有3种情况。
1、A恰好是末端节点
直接删掉

2、A只有一个非空子节点
要让该结点接替自己的位置

3、A有2个子节点
A必须找到左子树中最大的那个节点(或者)右子树中最小的那个节点来接替自己

Python实现
class Solution:
    def deleteNode(self, root: Optional[TreeNode], key: int) -> Optional[TreeNode]:
        #找该结点右子树中最小的结点
        #BST 最左边的就是最小的
        def getMin(node):
            while(node.left!=None):
                node=node.left
            return node
        
        if root==None: return 
        if(root.val==key):
            #判断该结点是否有左右子树(1、2情况)
            if root.left==None: return root.right //用右结点代替该结点
            if root.right==None: return root.left

            #情况3的处理:找该结点右子树中最小的
            minNode=getMin(root.right)

            #进行删除操作
            root.val=minNode.val
            root.right=self.deleteNode(root.right,minNode.val)
        elif root.val>key: #到左子树去找
            root.left=self.deleteNode(root.left,key)
        elif root.val<key: #右子树去找
            root.right=self.deleteNode(root.right,key)
        return root

在这里插入图片描述

Java实现
class Solution {
    public TreeNode deleteNode(TreeNode root, int key) {
        if (root == null) {
            return null;
        }
        if (root.val == key) {
            // 两个子结点有一个或者都为空
            if (root.left == null) {
                return root.right;
            }
            if (root.right == null) {
                return root.left;
            }
            // 两个子结点都不为空
            TreeNode minNode = getMin(root.right);
            root.val = minNode.val;
            root.right = deleteNode(root.right, minNode.val);
        } else if (root.val > key) {
            root.left = deleteNode(root.left, key);
        } else if (root.val < key) {
            root.right = deleteNode(root.right, key);
        }
        return root;
    }

    // 获得子结点中较小的那一个
    public TreeNode getMin(TreeNode node) {
        while (node.left != null) {
            node = node.left;
        }
        
        return node;
    }
}

在这里插入图片描述

你可能感兴趣的:(力扣,leetcode,算法)