538. 把二叉搜索树转换为累加树

给出二叉 搜索 树的根节点,该树的节点值各不相同,请你将其转换为累加树(Greater Sum Tree),使每个节点 node 的新值等于原树中大于或等于 node.val 的值之和。

链接

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
let total = 0

function convertBST(root: TreeNode | null): TreeNode | null {
total = 0
traverse(root)
return root
};

function traverse(root): TreeNode | null {
if (root === null) return null
traverse(root.right)
total += root.val
root.val = total
traverse(root.left)
}