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

73. 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

思路
递归

上一篇:【leetcode】501. Find Mode in Binary Search Tree


下一篇:力扣--根据前序、中序和后序来重建二叉树