二叉树中序遍历及后序遍历(下)
#encoding=utf-8
class TreeNode(object):
def __init__(self,var,left=None,right=None):
self.var=var
self.left=left
self.right=right
class PreOder(object):
retlist=[]
def __init__(self,root=None):
self.root=root
def preOder(self,node):#中序遍历整合到获取节点类
if node!=None:
self.preOder(node.left)
PreOder.retlist.append(node)
self.preOder(node.right)
return PreOder.retlist
def preOder_z(node,retlist):#中序遍历单独写函数
if node!=None:
preOder_x(node.left,retlist)
retlist.append(node)
preOder_z(node.right,retlist)
return retlist
def preOder_h(node,retlist):#后序遍历单独写函数
if node!=None:
preOder_h(node.left,retlist)
preOder_h(node.right,retlist)
retlist.append(node)
return retlist
if __name__=="__main__":
tree=TreeNode(1)
tree.left=TreeNode(2,left=TreeNode(4),right=TreeNode(5))
tree.right=TreeNode(3,left=TreeNode(6))#创建节点
content=PreOder(tree)#获取节点元素
#result_z=preOder_z(content.root,[])#中序遍历结果
#result_h=preOder_h(content.root,[])#后序遍历结果
#for i in result_x:
# print i.var,
#for i in result_z:
# print i.var,
#for i in result_h:
# print i.var,
result=content.preOder(content.root)#中序遍历整合后结果
print result