Python已知二叉树后序和中序遍历数组求前序遍历

题目描述

给出后续和中序数组,求前序数组。

示例

输入:
中序:[16, 8, 17, 6, 7, 5, 9]
后续:[8, 16, 6, 5, 7, 9, 17]
输出:
前序:[17, 16, 8, 9, 7, 6, 5]

方法

利用

代码

class Solution:
    def __init__(self):
        self.ans = []
    def compute(self, inorder, postorder):
        if not postorder or not inorder:
            return
        ch = postorder[-1]
        self.ans.append(ch)
        k = inorder.index(ch)
        self.compute(inorder[:k], postorder[:k])
        self.compute(inorder[k+1:], postorder[k:-1])
        return self.ans

if __name__ == "__main__":
    inlist = [16, 8, 17, 6, 7, 5, 9]
    postlist = [8, 16, 6, 5, 7, 9, 17]
    a = Solution().compute(inlist, postlist)
    print(a)

补充:已知前序和中序求后续遍历

class Solution:
    def __init__(self):
        self.ans = []
        
    def postcompute(self, inorder, preorder):
        if not preorder or not inorder:
            return
        ch = preorder[0]
        k = inorder.index(ch)
        self.postcompute(inorder[:k], preorder[1:k+1])
        self.postcompute(inorder[k+1:], preorder[k+1:])
        self.ans.append(ch)
        return self.ans

if __name__ == "__main__":
    prelist = [17, 16, 8, 9, 7, 6, 5]
    inlist = [16, 8, 17, 6, 7, 5, 9]
    post = Solution().postcompute(inlist, prelist)
    print(post)

参考
已知后序与中序排列,如何求先序排列?

你可能感兴趣的:(笔记,python,编程题,算法,深度优先,leetcode)