Leetcode: 从中序与后序遍历序列构造二叉树

根据一棵树的中序遍历与后序遍历构造二叉树。

中序遍历 inorder = [9,3,15,20,7]
后序遍历 postorder = [9,15,7,20,3]
   3
   / \
  9  20
    /  \
   15   7

Python 实现

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

class Solution(object):
    def buildTree(self, inorder, postorder):
        """
        :type inorder: List[int]
        :type postorder: List[int]
        :rtype: TreeNode
        """
        if not postorder or not inorder:
            return None;
        node = TreeNode(postorder[-1])
        mid = inorder.index(postorder[-1])
        node.left = self.buildTree(inorder[:mid],postorder[:mid])
        node.right = self.buildTree(inorder[mid+1:],postorder[mid:-1])
        return node
posted @ 2018-09-24 08:57  罗梁  阅读(290)  评论(0编辑  收藏  举报