538. 把二叉搜索树转换为累加树
为保证权益,题目请参考 538. 把二叉搜索树转换为累加树(From LeetCode).
解决方案1
Python
python
# 538. 把二叉搜索树转换为累加树
# https://leetcode-cn.com/problems/convert-bst-to-greater-tree/
# 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 convertBST(self, root: TreeNode) -> TreeNode:
self.t = 0
def rrr(root: TreeNode):
if root:
rrr(root.right)
root.val += self.t
self.t = root.val
rrr(root.left)
rrr(root)
return root
if __name__ == "__main__":
solution = Solution()
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
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