-
Notifications
You must be signed in to change notification settings - Fork 0
/
convertBST.py
53 lines (47 loc) · 1.26 KB
/
convertBST.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
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
'''
@File : convertBST.py
@Time : 2024/10/18 15:08:27
@Author : Zihao Zheng
@Email : [email protected]
'''
class Slution():
#右 中 左迭代的逻辑
def __init__(self) -> None:
self.pre=0
def convetBST(self,root):
if root is None:
return
self.convetBST(root.right)
self.pre=root.value+self.pre
root.value=self.pre
self.convetBST(root.left)
return root
def convetBST(self,root):
self.pre=0
self.traversal(root)
return root
def traversal(self, cur):
if cur is None:
return
self.traversal(cur.right)
cur.value += self.pre
self.pre = cur.value
self.traversal(cur.left)
def convertBST(self, root):
if not root: return root
stack = []
result = []
cur = root
pre = 0
while cur or stack:
if cur:
stack.append(cur)
cur = cur.right
else:
cur = stack.pop()
cur.val+= pre
pre = cur.val
cur =cur.left
return root