代码
class Node:
def __init__(self,value):
self.value = value
self.left = None
self.right = None
def add(self,value):
if value >= self.value:
if self.right == None:
self.right = Node(value)
else:
self.right.add(value)
else:
if self.left == None:
self.left = Node(value)
else:
self.left.add(value)
class BinarySearchTree:
def __init__(self,value):
self.root = Node(value)
def add(self,value):
self.root.add(value)
def preorder(self,T):
if T != None:
print(T.value)
self.preorder(T.left)
self.preorder(T.right)
def inorder(self,T):
if T != None:
self.inorder(T.left)
print(T.value)
self.inorder(T.right)
def postorder(self,T):
if T != None:
self.postorder(T.left)
self.postorder(T.right)
print(T.value)
if __name__ == '__main__':
arr = [1,3,6,7,3,4,9,11]
bT = BinarySearchTree(arr[0])
for i in range(1,len(arr)):
bT.add(arr[i])
print(bT.preorder(bT.root))
print(bT.inorder(bT.root))
print(bT.postorder(bT.root))