-
Notifications
You must be signed in to change notification settings - Fork 4
/
二叉搜索树与双向链表Boke.py
56 lines (49 loc) · 1.72 KB
/
二叉搜索树与双向链表Boke.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
class Solution:
def __init__(self):
self.listHead = None
self.listTail = None
# 将二叉树转换为有序双向链表
def Convert(self, pRootOfTree):
if pRootOfTree == None:
return
self.Convert(pRootOfTree.left)
if self.listHead == None:
self.listHead = pRootOfTree
self.listTail = pRootOfTree
else:
self.listTail.right = pRootOfTree
pRootOfTree.left = self.listTail
self.listTail = pRootOfTree
self.Convert(pRootOfTree.right)
return self.listHead
# 获得链表的正向序和反向序
def printList(self, head):
while head.right:
print(head.val, end=" ")
head = head.right
print(head.val)
while head:
print(head.val, end=" ")
head = head.left
# 给定二叉树的前序遍历和中序遍历,获得该二叉树
def getBSTwithPreTin(self, pre, tin):
if len(pre) == 0 | len(tin) == 0:
return None
root = TreeNode(pre[0])
for order, item in enumerate(tin):
if root.val == item:
root.left = self.getBSTwithPreTin(pre[1:order + 1], tin[:order])
root.right = self.getBSTwithPreTin(pre[order + 1:], tin[order + 1:])
return root
class TreeNode:
def __init__(self, x):
self.left = None
self.right = None
self.val = x
if __name__ == '__main__':
solution = Solution()
preorder_seq = [4, 2, 1, 3, 6, 5, 7]
middleorder_seq = [1, 2, 3, 4, 5, 6, 7]
treeRoot1 = solution.getBSTwithPreTin(preorder_seq, middleorder_seq)
head = solution.Convert(treeRoot1)
solution.printList(head)