-
Notifications
You must be signed in to change notification settings - Fork 0
/
buildTreeFromSortArray.py
71 lines (47 loc) · 1.7 KB
/
buildTreeFromSortArray.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
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
'''
@File : buildTreeFromSortArray.py
@Time : 2024/10/17 19:47:05
@Author : Zihao Zheng
@Email : [email protected]
'''
class TreeNode():
def __init__(self,val=0,left=None,right=None):
self.value=val
self.left=left
self.right=right
return
class Solution():
def bulidTree(self,inorder,postporder):
if not postporder:
return None
root_val =postporder[-1]
root=TreeNode(root_val)
separator_idx=inorder.index(root_val) #找到分割点
inorder_left=inorder[:separator_idx]
inorder_right=inorder[separator_idx+1:]
postporder_left=postporder[:len(inorder_left)]
postporder_right=postporder[len(inorder_left):len(postporder)-1]
root.left=self.bulidTree(inorder_left,postporder)
root.right=self.bulidTree(inorder_right,postporder_right)
return root
def bulidMaxTree(self,vals):
if not vals:
return None
root_val=max(vals)
root=TreeNode(root_val)
separator_idx=vals.index(root_val)
leftVals=vals[:separator_idx]
rightVals=vals[separator_idx+1:]
root.left=self.bulidMaxTree(leftVals)
root.right=self.bulidMaxTree(rightVals)
return root
def buildTreeFromSortArray(self,vals):
if not vals:
return None
mid =len(vals)//2
root=TreeNode(vals[mid])
root.left=self.buildTreeFromSortArray(vals[:mid])
root.right=self.buildTreeFromSortArray(vals[mid+1:])
return root