Leetcode 105. Construct Binary Tree from Preorder and Inorder Traversal

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

Medium

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

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

For example, given

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

Return the following binary tree:

    3
   / \
  9  20
    /  \
   15   7

 1 # Definition for a binary tree node.
 2 # class TreeNode:
 3 #     def __init__(self, x):
 4 #         self.val = x
 5 #         self.left = None
 6 #         self.right = None
 7 
 8 class Solution:
 9     def buildTree(self, preorder: List[int], inorder: List[int]) -> TreeNode:
10         idx = inorder.index( preorder.pop( 0 ) )
11         
12         node = TreeNode( inorder[ idx ] )
13         
14         node.left = buildTree( preorder, inorder[ 0:idx ] )
15         node.right = buildTree( preorder, inorder[ idx+1: ] )
16         
17         return node        
View Python Code

 

posted on 2019-07-17 20:26  浩然119  阅读(106)  评论(0编辑  收藏  举报