python实现:二叉树根据先序和中序获取后序

https://www.cnblogs.com/double-t/p/11151461.html

python实现:二叉树根据先序和中序获取后序_第1张图片

默写了一下


# class Tree():
#     def __init__(self,x):
#         self.value=x
#         self.left=None
#         self.right=None

# class Solution():
#     def resolution(self,preorder,inorder):
#         if not preorder:
#             return None
#         root = Tree(preorder[0])
#         pos_root = inorder.index(preorder[0])
#         root.left=self.resolution(preorder[1:pos_root+1],inorder[0:pos_root])
#         root.right = self.resolution(preorder[pos_root+1:],inorder[pos_root+1:])
#         return root
#     def postTravel(self,root):
#         if root !=None:
#             self.postTravel(root.left)
#             self.postTravel(root.right)
#             print(root.value)
class Node():
    def __init__(self,x):
        self.v = x
        self.left = None
        self.right = None

def getTree(pre,tin):
    if not pre:
        return None
    root = Node(pre[0])
    rootIndexInTin = tin.index(pre[0])
    root.left = getTree(pre[1:1+rootIndexInTin],tin[:rootIndexInTin])
    root.right = getTree(pre[1+rootIndexInTin:],tin[rootIndexInTin+1:])
    return root

def postTrval(root):
    if not root:
        #print("空树")
        return None
    postTrval(root.left)
    postTrval(root.right)
    print(root.v," ")
    return "结束"

pre=[1,2,4,7,3,5,6,8]
tin=[4,7,2,1,5,3,8,6]

tree = getTree(pre,tin)
postTrval(tree)

 

你可能感兴趣的:(算法)