-
Notifications
You must be signed in to change notification settings - Fork 0
/
26.二叉搜索树与双向链表.py
58 lines (49 loc) · 1.54 KB
/
26.二叉搜索树与双向链表.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
# # -*- coding:utf-8 -*-
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
# class Solution:
# def Convert(self, pRootOfTree):
# # write code here
# LastNodeInList = ListNode([])
# LastNodeInList = self.ConvertTreeToList(pRootOfTree, LastNodeInList)
# return LastNodeInList
# def ConvertTreeToList(self, pRootOfTree, LastNodeInList):
# if not pRootOfTree:
# return
# if not pRootOfTree.left:
# self.Convert(pRootOfTree.left)
# LastNodeInList.next = pRootOfTree.left
# LastNodeInList.next = pRootOfTree
# if not pRootOfTree.right:
# self.Convert(pRootOfTree.right)
# return LastNodeInList
# -*- coding:utf-8 -*-
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def Convert(self, pRootOfTree):
# write code here
if not pRootOfTree:
return
self.attr = []
self.midorder(pRootOfTree)
for i,v in enumerate(self.attr[:-1]):
v.right = self.attr[i+1] #向右延伸
self.attr[i+1].left = v #向左延伸
return self.attr[0]
def midorder(self, root):
if not root:
return
self.midorder(root.left)
self.attr.append(root)
self.midorder(root.right)