Skip to content

Commit 8ad16e0

Browse files
author
weiy
committedSep 29, 2018
construct binary tree from inorder and postorder traversal medium
1 parent 97eff51 commit 8ad16e0

File tree

1 file changed

+92
-0
lines changed

1 file changed

+92
-0
lines changed
 
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,92 @@
1+
"""
2+
Given inorder and postorder traversal of a tree, construct the binary tree.
3+
4+
Note:
5+
You may assume that duplicates do not exist in the tree.
6+
7+
For example, given
8+
9+
inorder = [9,3,15,20,7]
10+
postorder = [9,15,7,20,3]
11+
Return the following binary tree:
12+
13+
3
14+
/ \
15+
9 20
16+
/ \
17+
15 7
18+
19+
20+
这个的思路与之前的大同小异。
21+
22+
inorder:
23+
24+
左 根 右
25+
26+
postorder:
27+
28+
左 右 根
29+
30+
postorder 中找根,
31+
inorder 中找左右。
32+
33+
下面是一个递归实现。
34+
35+
left_inorder
36+
left_postorder
37+
38+
right_inorder
39+
right_postorder
40+
的处理。
41+
42+
一开始全部中规中矩的定义清晰,然后root.left, root.right。
43+
44+
完成所有测试大概需要 200ms 左右。
45+
46+
后面发现并不需要:
47+
48+
postoder 是 左 右 根。
49+
根完了就是右,所以直接可以postorder.pop(),然后先进行 right 的查找,相当于 right_postorder 带了一些另一颗树的东西,不过无关紧要。
50+
51+
都是些优化的步骤。
52+
53+
测试地址:
54+
https://leetcode.com/problems/construct-binary-tree-from-inorder-and-postorder-traversal/
55+
56+
"""
57+
# Definition for a binary tree node.
58+
# class TreeNode(object):
59+
# def __init__(self, x):
60+
# self.val = x
61+
# self.left = None
62+
# self.right = None
63+
64+
class Solution(object):
65+
def buildTree(self, inorder, postorder):
66+
"""
67+
:type inorder: List[int]
68+
:type postorder: List[int]
69+
:rtype: TreeNode
70+
"""
71+
72+
def makeTree(inorder,
73+
postorder):
74+
if not inorder or not postorder:
75+
return None
76+
77+
root = TreeNode(postorder.pop())
78+
index = inorder.index(root.val)
79+
80+
# left_inorder = inorder[:inorder.index(root.val)]
81+
# left_postorder = postorder[:len(left_inorder)]
82+
83+
# right_inorder = inorder[len(left_inorder)+1:]
84+
# right_postorder = postorder[len(left_postorder):-1]
85+
86+
87+
root.right = makeTree(inorder[index+1:], postorder)
88+
root.left = makeTree(inorder[:index], postorder)
89+
90+
return root
91+
92+
return makeTree(inorder, postorder)

0 commit comments

Comments
 (0)
Please sign in to comment.