File tree Expand file tree Collapse file tree 1 file changed +44
-0
lines changed Expand file tree Collapse file tree 1 file changed +44
-0
lines changed Original file line number Diff line number Diff line change
1
+ # LeetCode 105 Construct Binary Tree from Preorder and Inorder Traversal
2
+ ## 1. Description
3
+ Given preorder and inorder traversal of a tree, construct the binary tree.
4
+
5
+ Note:
6
+ You may assume that duplicates do not exist in the tree.
7
+
8
+ For example, given
9
+
10
+ preorder = [ 3,9,20,15,7]
11
+ inorder = [ 9,3,15,20,7]
12
+ Return the following binary tree:
13
+
14
+ 3
15
+ / \
16
+ 9 20
17
+ / \
18
+ 15 7
19
+
20
+ ## 2. Solution
21
+ ``` python
22
+ # Definition for a binary tree node.
23
+ # class TreeNode:
24
+ # def __init__(self, x):
25
+ # self.val = x
26
+ # self.left = None
27
+ # self.right = None
28
+
29
+ class Solution :
30
+ def buildTree (self , preorder , inorder ):
31
+ """
32
+ :type preorder: List[int]
33
+ :type inorder: List[int]
34
+ :rtype: TreeNode
35
+ """
36
+ if len (preorder) == 0 :
37
+ return None
38
+ if len (preorder) == 1 :
39
+ return TreeNode(preorder.pop(0 ))
40
+ root = TreeNode(preorder.pop(0 ))
41
+ root.left = self .buildTree(preorder[:inorder.index(root.val)], inorder[:inorder.index(root.val)])
42
+ root.right = self .buildTree(preorder[inorder.index(root.val):], inorder[inorder.index(root.val)+ 1 :])
43
+ return root
44
+ ```
You can’t perform that action at this time.
0 commit comments