求优化——二叉树
题目:已知某二叉树中序遍历结果为cbedahgijf、后序遍历结果为cedbhjigfa,编程实现二叉树的二叉链表示法,并输出先序遍历结果。class BTNode:
def __init__(self,data=None,lchild=None,rchild=None):
self.data=data
self.lchild=lchild
self.rchild=rchild
def CreateBTNode(post,im,length):
if (length<=0):
return None
s=BTNode(post[-1])
k=-1
for p in im:
k+=1
if p==s.data:
break
s.lchild=CreateBTNode(post[0:k],im[0:k],k)
s.rchild=CreateBTNode(post[k:length-1],im[k+1:],length-k-1)
return s
def predis(s):
if s!=None:
print(s.data,end="")
predis(s.lchild)
predis(s.rchild)
if __name__=='__main__':
im=input('请输入中序遍历结果:')
post=input('请输入后序遍历结果:')
length=len(im)
predis(CreateBTNode(post,im,length))
print("")