-
-
Notifications
You must be signed in to change notification settings - Fork 8.8k
/
Copy pathSolution.py
28 lines (28 loc) · 881 Bytes
/
Solution.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
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def bstToGst(self, root: TreeNode) -> TreeNode:
s = 0
node = root
while root:
if root.right is None:
s += root.val
root.val = s
root = root.left
else:
next = root.right
while next.left and next.left != root:
next = next.left
if next.left is None:
next.left = root
root = root.right
else:
s += root.val
root.val = s
next.left = None
root = root.left
return node