# coding:utf-8
class Node(object):
def __init__(self, item):
self.elem = item
self.lchild = None
self.rchild = None
class Tree(object):
# 初始化
def __init__(self):
self.root = None
# 广度遍历
def breadthTravel(self):
if self.root is None:
return
queue = [] # 队列
queue.append(self.root) # 入队
while queue:
current_node = queue.pop(0) # 出队
print(current_node.elem,end='')
if current_node.lchild is not None:
queue.append(current_node.lchild)
if current_node.rchild is not None:
queue.append(current_node.rchild)
def preOrder(self, node): # 传递根是为了递归把每棵树的子树的根传入
if node is None:
return
print(node.elem,end='')
self.preOrder(node.lchild)
self.preOrder(node.rchild)
def inOrder(self, node):
if node is None:
return
self.inOrder(node.lchild)
print(node.elem,end='')
self.inOrder(node.rchild)
def postOrder(self,node):
if node is None:
return
self.postOrder(node.lchild)
self.postOrder(node.rchild)
print(node.elem,end='')
# 树的添加结点
def add(self, item):
node = Node(item)
if self.root is None: # 根节点是否本身为空
self.root = node
return
queue = [] # 队列
queue.append(self.root) # 入队
while queue: # 当列表不为空
current_node = queue.pop(0) # 出队
if current_node.lchild is None:
current_node.lchild = node
return
else:
queue.append(current_node.lchild)
if current_node.rchild is None:
current_node.rchild = node
return
else:
queue.append(current_node.rchild)
if __name__ == "__main__":
tree = Tree()
tree.add(1)
tree.add(2)
tree.add(3)
tree.add(4)
tree.add(5)
tree.add(6)
tree.add(7)
tree.add(8)
tree.add(9)
tree.breadthTravel()
print('')
tree.preOrder(tree.root)
print('')
tree.inOrder(tree.root)
print('')
tree.postOrder(tree.root)