# -*- coding: utf-8 -*- # @file: binary_tree.py from graphviz import Digraph import uuid from random import sample
# 二叉树类 classBTree(object): # 初始化 def__init__(self, data=None, left=None, right=None): self.data = data # 数据域 self.left = left # 左子树 self.right = right # 右子树 self.dot = Digraph(comment='Binary Tree')
# 前序遍历,实现思路:递归 defpre_order(self): if self.data isnotNone: print(self.data, end=' ') if self.left isnotNone: self.left.pre_order() if self.right isnotNone: self.right.pre_order()
# 中序遍历,实现思路:递归 defin_order(self): if self.left isnotNone: self.left.in_order() if self.data isnotNone: print(self.data, end=' ') if self.right isnotNone: self.right.in_order()
# 后序遍历,实现思路:递归 defpost_order(self): if self.left isnotNone: self.left.post_order() if self.right isnotNone: self.right.post_order() if self.data isnotNone: print(self.data, end=' ')
# 层次遍历, 实现思路:利用队列 deflevel_order(self): if self.data isNone: return [] queue = [self] res = [] while queue: tmp = [] for i inrange(len(queue)): node = queue.pop(0) tmp.append(node.data) if node.left: queue.append(node.left) if node.right: queue.append(node.right) res.append(tmp) return res
# A utility function to insert a new node with the given key definsert(self, root, node): if root isNone: root = node else: if root.data < node.data: if root.right isNone: root.right = node else: self.insert(root.right, node) else: if root.left isNone: root.left = node else: self.insert(root.left, node)
# check if the new data is in BST defisInBST(self, root, new_data): if root isNone: returnFalse else: if root.data == new_data: returnTrue elif root.data < new_data: return self.isInBST(root.right, new_data) else: return self.isInBST(root.left, new_data)
# search for new data, return a BST whose root is new data defsearch(self, root, new_data): inflag = self.isInBST(root, new_data) ifnot inflag: print("%s is not in BST." % new_data) else: if root.data == new_data: return root elif root.data < new_data: return self.search(root.right, new_data) else: return self.search(root.left, new_data)
# find the node which has the minimum value deffindMinNode(self, root): if root isNone: returnNone elif root.left isNone: return root else: return self.findMinNode(root.left)
# A utility function to delete a node with given data defdelNode(self, root, val): # 删除二叉搜索树中值为val的点 if root isNone: return if val < root.data: root.left = self.delNode(root.left, val) elif val > root.data: root.right = self.delNode(root.right, val) # 当val == root.val时,分为三种情况:只有左子树或者只有右子树、有左右子树、即无左子树又无右子树 else: if root.left and root.right: # 既有左子树又有右子树,则需找到右子树中最小值节点 temp = self.findMinNode(root.right) root.data = temp.data # 再把右子树中最小值节点删除 root.right = self.delNode(root.right, temp.data) elif root.right isNoneand root.left isNone: # 左右子树都为空 root = None elif root.right isNone: # 只有左子树 root = root.left elif root.left isNone: # 只有右子树 root = root.right return root