二叉树实现广度和深度优先
__author__ = "Hao Rui Chun"
class Node(object):
def __init__(self,item):
self.item =item
self.lchild = None
self.rchild = None
class Tree(object):
def __init__(self):
self.root = None
def add(self,item):
node = Node(item)
if self.root == None:
self.root = node
return
else:
queue = [self.root]
while queue:
cur_value = queue.pop(0)
if cur_value.lchild == None:
cur_value.lchild = node
return
else:
queue.append(cur_value.lchild)
if not cur_value.rchild:
cur_value.rchild = node
return
else:
queue.append(cur_value.rchild)
def breath_travel(self):
"""广度遍历"""
if self.root == None:
return
queue =[self.root]
while queue:
cur_code = queue.pop(0)
print(cur_code.item,end=' ')
if cur_code.lchild:
queue.append(cur_code.lchild)
if cur_code.rchild:
queue.append(cur_code.rchild)
def preorder(self,node):
"""深度遍历:先序遍历(根->左->右)"""
if node == None:
return
print(node.item,end=' ')
self.preorder(node.lchild)
self.preorder(node.rchild)
def inorder(self,node):
"""深度遍历:中序遍历(左->根->右)"""
if node == None:
return
self.inorder(node.lchild)
print(node.item,end=' ')
self.inorder(node.rchild)
def postorder(self,node):
"""深度遍历:后序遍历(左->右->根)"""
if node == None:
return
self.postorder(node.lchild)
self.postorder(node.rchild)
print(node.item,end=' ')
def getleaf(self,node):
if node == None:
return
if node.lchild == None and node.rchild == None:
print(node.item,end=' ')
self.getleaf(node.lchild)
self.getleaf(node.rchild)
if __name__ == '__main__':
tree = Tree()
tree.add('A')
tree.add('B')
tree.add('C')
tree.add('D')
tree.add('E')
tree.add('F')
tree.add('G')
tree.add('H')
tree.add('I')
tree.add('J')
print('层序遍历结果:', end=' ')
tree.breath_travel()
print('\t')
print('先序遍历结果:',end=' ')
tree.preorder(tree.root)
print('\t')
print('中序遍历结果:', end=' ')
tree.inorder(tree.root)
print('\t')
print('后序遍历结果:', end=' ')
tree.postorder(tree.root)
print('\t')
print('获取所有叶子节点:', end=' ')
tree.getleaf(tree.root)