leetcode-106-根据中序和后序遍历,构造二叉树

题目描述:

Given inorder and postorder traversal of a tree, construct the binary tree.

Note:

You may assume that duplicates do not exist in the tree.

For example, given

inorder = [9,3,15,20,7]

postorder = [9,15,7,20,3]
Return the following binary tree:

    3
   / \
  9  20
    /  \
   15   7


inorder =   [6,8,4,9,3,15,20,7]
postorder = [6,4,8,9,15,7,20,3]
            3
           / \
          9  20
         /  /  \
        8  15   7
       / \
      6  4 ps: 以 postorder为中心进行分类

题目分析:根据中序和后序遍历,构造二叉树。 根据动态规划方法,找出循环的共性。
构造子二叉树,需要节点,和左右连接,从后序遍历找出根节点,从inorder对目标序列进行切分,如此往复。

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

class Solution:
    def buildTree(self, inorder, postorder):
        """
        :type inorder: List[int]
        :type postorder: List[int]
        :rtype: TreeNode
        """
        if not postorder:
            return None
        node_center_frompost=postorder.pop()
        index_center_inorder=inorder.index(node_center_frompost)
        node=TreeNode(node_center_frompost)
        node.left=self.buildTree(inorder[:index_center_inorder],postorder[:index_center_inorder])
        node.right=self.buildTree(inorder[index_center_inorder+1:],postorder[index_center_inorder:])
        return node

    原文作者:龙仔
    原文地址: https://segmentfault.com/a/1190000014248667
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞