[Lintcode]73. Construct Binary Tree from Preorder and Inorder Traversal/[Leetcode]105. Construct Binary Tree from Preorder and Inorder Traversal

73. Construct Binary Tree from Preorder and Inorder Traversal/[105. Construct Binary Tree from Preorder and Inorder Traversal

](https://leetcode.com/problems/construct-binary-tree-from-preorder-and-inorder-traversal/)

  • 本题难度: Medium
  • Topic: Binary Tree

Description

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

Example
Example 1:
Input: [], []
Output: null

Example 2:
Input: in-order = [1,2,3], pre-order = [2,1,3]
Output:

  2
 / \
1   3

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

我的代码

"""
Definition of TreeNode:
class TreeNode:
    def __init__(self, val):
        self.val = val
        self.left, self.right = None, None
"""

class Solution:
    """
    @param inorder: A list of integers that inorder traversal of a tree
    @param postorder: A list of integers that postorder traversal of a tree
    @return: Root of a tree
    """
    def buildTree(self, preorder, inorder):
        # write your code here
        if preorder and inorder:
            res = TreeNode(preorder[0])
            index = inorder.index(preorder.pop(0))
            res.left = self.buildTree(preorder,inorder[0:index])
            res.right = self.buildTree(preorder,inorder[index+1:])
            return res
        else:
            return None

思路
递归

posted @ 2019-02-14 21:40  siriusli  阅读(83)  评论(0编辑  收藏  举报