二叉树的前序遍历为:{1,2,4,7,3,5,6,8},中序遍历为:{4,7,2,1,5,3,8,6},求后序遍历
# -*- coding:utf-8 -*-
class Node:
def __init__(self, x):
self.data = x
self.lchild = None
self.rchild = None
class Solution:
def __init__(self):
self.list=[]
def reConstructBinaryTree(self, pre, tin):
if len(tin)==0 or len(pre)==0:
self.list.append(Node(-1))
return Node(-1)
data = pre.pop(0)
root=Node(data)
index=tin.index(data)
#递归得到后序遍历
root.lchild=self.reConstructBinaryTree(pre,tin[0:index])
root.rchild=self.reConstructBinaryTree(pre,tin[index+1:])
self.list.append(root)
return root
#层次遍历
def level_queueAndStack(self,root):
if root==None:
return
stack_1=[]
stack_2=[]
stack_1.append(root)
stack_2.append(root)
while stack_1:
node=stack_1.pop(0)
if node.lchild:
stack_1.append(node.lchild)
stack_2.append(node.lchild)
if node.rchild:
stack_1.append(node.rchild)
stack_2.append(node.rchild)
while stack_2:
print stack_2.pop(0).data,
s=Solution()
s.reConstructBinaryTree([1,2,4,7,3,5,6,8],[4,7,2,1,5,3,8,6])
#输出树的后序遍历
l=[i.data for i in s.list if i.data!=-1]
print l
s.level_queueAndStack(s.list.pop())
输出结果:
[7, 4, 2, 5, 8, 6, 3, 1]
1 2 3 4 -1 5 6 -1 7 -1 -1 8 -1 -1 -1 -1 -1