Skip to content

Commit 6922e1a

Browse files
committed
2018.12.08 LeetCode 105
1 parent 55d10e9 commit 6922e1a

File tree

1 file changed

+44
-0
lines changed

1 file changed

+44
-0
lines changed

2018.12.08-leetcode105/Despacito.md

Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
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+
```

0 commit comments

Comments
 (0)