Skip to content

Commit d1d7da5

Browse files
committed
2018.12.09 LeetCode 106
1 parent 6922e1a commit d1d7da5

File tree

1 file changed

+48
-0
lines changed

1 file changed

+48
-0
lines changed

2018.12.09-leetcode106/Despacito.md

Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
# LeetCode 106 Construct Binary Tree from Inorder and Postorder Traversal
2+
## 1. Description
3+
4+
Given inorder and postorder traversal of a tree, construct the binary tree.
5+
6+
**Note:**
7+
8+
You may assume that duplicates do not exist in the tree.
9+
10+
For example, given
11+
12+
inorder = [9,3,15,20,7]
13+
14+
postorder = [9,15,7,20,3]
15+
16+
Return the following binary tree:
17+
18+
3
19+
/ \
20+
9 20
21+
/ \
22+
15 7
23+
24+
## 2. Solution
25+
```python
26+
# Definition for a binary tree node.
27+
# class TreeNode:
28+
# def __init__(self, x):
29+
# self.val = x
30+
# self.left = None
31+
# self.right = None
32+
33+
class Solution:
34+
def buildTree(self, inorder, postorder):
35+
"""
36+
:type inorder: List[int]
37+
:type postorder: List[int]
38+
:rtype: TreeNode
39+
"""
40+
if len(postorder) == 0:
41+
return None
42+
if len(postorder) == 1:
43+
return TreeNode(postorder[0])
44+
root = TreeNode(postorder.pop())
45+
root.left = self.buildTree(inorder[:inorder.index(root.val)], postorder[:inorder.index(root.val)])
46+
root.right = self.buildTree(inorder[inorder.index(root.val)+1:], postorder[inorder.index(root.val):])
47+
return root
48+
```

0 commit comments

Comments
 (0)