-
Notifications
You must be signed in to change notification settings - Fork 614
/
106.py
53 lines (44 loc) · 1.28 KB
/
106.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
'''
Given inorder and postorder traversal of a tree, construct the binary tree.
Note:
You may assume that duplicates do not exist in the tree.
For example, given
inorder = [9,3,15,20,7]
postorder = [9,15,7,20,3]
Return the following binary tree:
3
/ \
9 20
/ \
15 7
'''
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def buildTree(self, inorder, postorder):
"""
:type inorder: List[int]
:type postorder: List[int]
:rtype: TreeNode
"""
self.index = len(inorder)-1
def recursive(postorder, inorder, start, end):
if start > end:
return None
node = TreeNode(postorder[self.index])
self.index -= 1
if start == end:
return node
search_index = 0
for i in range(start, end+1):
if inorder[i] == node.val:
search_index = i
break
node.right = recursive(postorder, inorder, search_index+1, end)
node.left = recursive(postorder, inorder, start, search_index-1)
return node
return recursive(postorder, inorder, 0, len(inorder)-1)