コード例 #1
0
    def tree_insert(self, z: TreeNode):
        y = None
        x = self.head
        while x:
            y = x
            x = x.left if z.value < x.value else x.right

        z.parent = y

        if not y:
            self.head = z

        elif z.value < y.value:
            y.left = z

        else:
            y.right = z
コード例 #2
0
    def transplant(self, u: TreeNode, v: TreeNode):
        """

            NB: transplant() doesn't attempt to update v.left and v.right
                doing so, or not doing so, is the responsibility of transplant()'s caller
        :param u:
        :param v:
        :return:
        """
        if not u.parent:
            self.head = v

        elif u == u.parent.left:
            u.parent.left = v

        else:
            u.parent.right = v

        if not v:
            v.parent = u.parent
コード例 #3
0
    def insert(self, key: int):
        if self.root is None:
            self.root = TreeNode(key)
            return

        parent = self.root
        if parent.key == key:
            raise KeyError("Repeated key")
        child = parent.left if key < parent.key else parent.right

        while child is not None:
            parent = child
            if parent.key == key:
                raise KeyError("Repeated key")
            child = child.left if key < child.key else child.right

        newNode = TreeNode(key)
        newNode.parent = parent

        if newNode.key < parent.key:
            parent.left = newNode
        else:
            parent.right = newNode
コード例 #4
0
        if root != parent.right:
            break
        root = parent
        parent = parent.parent
    return parent


if __name__ == "__main__":
    twenty = TreeNode(20)
    eight = TreeNode(20)
    four = TreeNode(4)
    twelve = TreeNode(12)
    ten = TreeNode(10)
    fourteen = TreeNode(14)
    twentytwo = TreeNode(22)
    # setting Parents
    eight.parent = twenty
    four.parent = eight
    twelve.parent = eight
    ten.parent = twelve
    fourteen.parent = twelve
    twentytwo.parent = twenty
    # left right
    twenty.right = twentytwo
    twenty.left = eight
    eight.left = four
    eight.right = twelve
    twelve.left = ten
    twelve.right = fourteen
    print(successor(fourteen).value)