class Node(object):
"""
定义树节点类
"""
def __init__ (self,x):
self.val=x
self.lchild=None
self.rchild=None
class Tree(object):
"""
构造树
"""
def __init__ (self):#初始化根节点
self.root=None
def add(self,data):#按层序增加树结点
node=Node(data)
if self.root is None:
self.root=node
else:
q=[self.root]
while True:
pop_node=q.pop(0)
if pop_node.lchild is None:
pop_node.lchild=node
return
elif pop_node.rchild is None:
pop_node.rchild=node
return
q.append(pop_node.lchild)
q.append(pop_node.rchild)
class traverse(object):
"""
几种遍历得实现
"""
def preorder(self,root):#先序遍历
if root==None:
return
print(root.val,end=' ')
self.preorder(root.lchild)
self.preorder(root.rchild)
def inorder(self,root):#中序遍历
if root==None:
return
self.preorder(root.lchild)
print(root.val,end=' ')
self.preorder(root.rchild)
def postorder(self,root):#后序遍历
if root==None:
return
self.preorder(root.lchild)
self.preorder(root.rchild)
print(root.val,end=' ')
t=Tree()
tra=traverse()
for i in range(10):
t.add(i)
print("先序遍历:",end=' ')
tra.preorder(t.root)
print("\n中序遍历:",end=' ')
tra.inorder(t.root)
print("\n后序遍历:",end=' ')
tra.postorder(t.root)
运行结果: