LeetCode889:根据前序和后序遍历构造二叉树

目录

一、题目

二、示例

三、思路

四、代码


一、题目

返回与给定的前序和后序遍历匹配的任何二叉树。

 pre 和 post 遍历中的值是不同的正整数。

二、示例

示例:

输入:pre = [1,2,4,5,3,6,7], post = [4,5,2,6,7,3,1]
输出:[1,2,3,4,5,6,7]

提示:

  • 1 <= pre.length == post.length <= 30
  • pre[] 和 post[] 都是 1, 2, ..., pre.length 的排列
  • 每个输入保证至少有一个答案。如果有多个答案,可以返回其中一个。

三、思路

先序遍历:根-->左-->右

后序遍历:左-->右-->根

先序遍历+后序遍历 无法确定一个独一无二的二叉树,因为只有中序遍历可以确定该结点为左孩子还是右孩子,先序和后序只可确定根节点,除非结点的度数为2或0.

  1. 用前序遍历的第一个元素创建出根节点
  2. 用前序遍历的第二个元素x,去后序遍历中找对应的下标y,将y+1就能得到左子树的个数了
  3. 将前序数组,后序数组拆分左右两部分
  4. 递归的处理前序数组左边、后序数组右边
  5. 递归的处理前序数组右边、后序数组右边
  6. 返回根节点

四、代码

# Definition for a binary tree node.
class TreeNode:
    def __init__(self, x):
        self.val = x
        self.left = None
        self.right = None

    def __repr__(self):
        return str(self.val)

class Solution:
    def constructFromPrePost(self, pre, post):
        if (len(pre) == 0):
            return None
        root = TreeNode(pre[0])
        if (len(pre) == 1): return root
        for i in range(len(post)):
            if (post[i] == pre[1]):
                root.left = self.constructFromPrePost(pre[1:i + 2], post[0:i + 1])
                root.right = self.constructFromPrePost(pre[i + 2:], post[i + 1:-1])
                return root

if __name__ == '__main__':
    pre = [1, 2, 4, 5, 3, 6, 7]
    post = [4, 5, 2, 6, 7, 3, 1]
    s = Solution()
    root = s.constructFromPrePost(pre, post)
    print(root)

猜你喜欢

转载自blog.csdn.net/weixin_45666660/article/details/108794456