python 二叉搜索樹相關代碼

class TreeNode:
    def __init__(self, val):
        self.val = val
        self.left = None
        self.right = None


class OperationTree:
    def insert(self, root, val):
        if root is None:
            root = TreeNode(val)

        elif val < root.val:
            root.left = self.insert(root.left, val)
        elif val > root.val:
            root.right = self.insert(root.right, val)
        return root

    def printTree(self, root):
        if root is None:
            return
        self.printTree(root.left)
        print(root.val, end=' ')
        self.printTree(root.right)

    def query(self, root):
        if root is None:
            return
        if val == root.val:
            return True
        elif val < root.val:
            self.query(root.left)
        elif val > root.right:
            self.query(root.right)

    def find_min(self, root):
        if root.left:
            return self.find_min(root.left)
        else:
            return root

    def find_max(self, root):
        if root.right:
            return self.find_max(root.right)
        else:
            return root

    def del_node(self, root, val):
        if root is None:
            return
        if val < root.val:
            root.left = self.del_node(root.left, val)
        elif val > root.val:
            root.right = self.del_node(root.right, val)
        # 當val == root.val時,分爲三種狀況:只有左子樹或者只有右子樹、有左右子樹、即無左子樹又無右子樹
        else:
            if root.left and root.right:
                # 既有左子樹又有右子樹,則需找到右子樹中最小值節點
                temp = self.find_min(root.right)
                root.val = temp.val
                # 再把右子樹中最小值節點刪除,讓它符合二叉搜索樹的定義
                root.right = self.del_node(root.right, temp.val)
            elif root.right is None and root.left is None:
                # 左右子樹都爲空
                root = None
            elif root.right is None:
                # 只有左子樹
                root = root.left
            elif root.left is None:
                # 只有右子樹
                root = root.right
        return root


if __name__ == '__main__':
    List = [17, 5, 35, 2, 11, 29, 38, 9, 16, 8]
    root = None
    op = OperationTree()
    for val in List:
        root = op.insert(root, val)
    print('中序打印二叉搜索樹:', end=' ')
    op.printTree(root)
相關文章
相關標籤/搜索