-
Notifications
You must be signed in to change notification settings - Fork 78
/
Copy path4.py
46 lines (34 loc) · 1.07 KB
/
4.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
# -*- coding:utf-8 -*-
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
# 返回构造的TreeNode根节点
def reConstructBinaryTree(self, pre, tin):
# write code here
headNode = TreeNode(pre[0])
centureIndex = tin.index(pre[0])
left = tin[0:centureIndex]
right = tin[centureIndex + 1:]
if len(left) == 0:
leftNode = None
elif len(left) == 1:
leftNode = TreeNode(left[0])
else:
leftNode = self.reConstructBinaryTree(pre[1:1 + len(left)], left)
if len(right) == 0:
rightNode = None
elif len(right) == 1:
rightNode = TreeNode(right[0])
else:
rightNode = self.reConstructBinaryTree(pre[1 + len(left):], right)
headNode.left = leftNode
headNode.right = rightNode
return headNode
solution = Solution()
pre = [1, 2, 4, 3, 5, 6]
tin = [4, 2, 1, 5, 3, 6]
headNode = solution.reConstructBinaryTree(pre, tin)
print headNode