classBST: def__init__(self, seq=None): """ :param seq: the optional parameter, to initialize the tree """ self.root = None self.insert(seq)
definsert(self, val_list): """ insert value into the tree :param val_list: integer or list, the value waiting for inserting :return: """ if isinstance(val_list, list): if self.root isNone: self.root = Node(val_list.pop(0)) for v in val_list: self.__ins(v) elif isinstance(val_list, int): self.__ins(val_list)
def__ins(self, v): """ insert a value into the tree :param v: interger :return: """ new_node = Node(v) tmp = self.root while tmp: if v > tmp.value: if tmp.right: tmp = tmp.right else: tmp.right = new_node break elif v < tmp.value: if tmp.left: tmp = tmp.left else: tmp.left = new_node break
defsearch(self, val): """ find the specific value :param val: :return: """ tmp = self.root while tmp: if val == tmp.value: print("查找成功^_^") break elif val > tmp.value: if tmp.right: tmp = tmp.right else: print("查找失败x_x") break elif val < tmp.value: if tmp.left: tmp = tmp.left else: print("查找失败x_x") break