#coding:utf-8
class Node(object):
"""二叉树中的节点对象"""
def __init__(self,item):
self.item=item
self.lchild=None
self.rchild=None
class BinaryTree(object):
"""二叉树"""
def __init__(self):
self.root=None
def add(self,item):
"""往二叉树中添加节点,把当前的二叉树当成满二叉树
从上到下,从左到右顺序添加
A B C D E F G H I J k 队列:从一端插入,另外一端移出
"""
new_node =Node(item)
if self.root==None:
self.root=new_node
return
queue =[self.root]
while queue:
cursor=queue.pop(0)
if cursor.lchild==None:
cursor.lchild=new_node
return
else:
queue.append(cursor.lchild)
if cursor.rchild==None:
cursor.rchild=new_node
return
else:
queue.append(cursor.rchild)
def iterate(self):
"""遍历二叉树,采用从上到下,从左到右顺序遍历"""
queue = [self.root]
while queue:
cursor = queue.pop(0)
print(cursor.item,end="\t")
if cursor.lchild!=None:
queue.append(cursor.lchild)
if cursor.rchild !=None:
queue.append(cursor.rchild)
print("")
"""二叉树的深度优先遍历:先序遍历,中序遍历,后序遍历"""
def pre_iterate(self,node):
"""先序遍历:根-左-右"""
if node==None: #定义边界
return
root=node
print(root.item,end="\t")
self.pre_iterate(root.lchild)
self.pre_iterate(root.rchild)
def mid_iterate(self,node):
"""中序遍历:左-根-右"""
if node==None: #定义边界
return
root=node
self.mid_iterate(root.lchild)
print(root.item,end="\t")
self.mid_iterate(root.rchild)
def post_iterate(self,node):
"""后序遍历:左-右-根"""
if node==None: #定义边界
return
root=node
self.post_iterate(root.lchild)
self.post_iterate(root.rchild)
print(root.item,end="\t")
if __name__ == '__main__':
tree =BinaryTree()
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")
tree.iterate()
tree.pre_iterate(tree.root)
print("")
tree.mid_iterate(tree.root)
print("")
tree.post_iterate(tree.root)