コード例 #1
0
    def delete(self, num: int, node: TreeNode = None):
        node = node or self.root

        if num < node.val:
            node.left = self.delete(num, node.left)
        elif num > node.val:
            node.right = self.delete(num, node.right)
        else:
            self.size -= 1

            if node.left is None and node.right is None:
                if self.root == node:
                    self.root = None
                return None
            elif node.left is None:
                if self.root == node:
                    self.root = node.right
                return node.right
            elif node.right is None:
                if self.root == node:
                    self.root = node.left
                return node.left
            else:
                min_node = node.right
                while min_node.left:
                    min_node = min_node.left

                node.val = min_node.val
                node.right = self.delete(min_node.val, node.right)

        return node
コード例 #2
0
ファイル: BinarySearchTree.py プロジェクト: zeroam/algorithm
    def delete(self, node: TreeNode, val: int):
        if node is None:
            return

        if val < node.val:
            node.left = self.delete(node.left, val)

        if val > node.val:
            node.right = self.delete(node.right, val)

        if val == node.val:
            if node.left and node.right:
                predecessor = node.left
                while predecessor.right:
                    predecessor = predecessor.right

                node.val = predecessor.val
                predecessor.val = val
                node.left = self.delete(node.left, val)
            elif node.left:
                return node.left
            elif node.right:
                return node.right
            else:
                return None

        return node