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
58
59
60
61
62
63
64
65
66
67
68
69
// @Title: 把二叉搜索树转换为累加树 (Convert BST to Greater Tree)
// @Author: 15816537946@163.com
// @Date: 2020-06-25 07:15:36
// @Runtime: 16 ms
// @Memory: 6.5 MB
/*
 * @lc app=leetcode.cn id=538 lang=golang
 *
 * [538] 把二叉搜索树转换为累加树
 *
 * https://leetcode-cn.com/problems/convert-bst-to-greater-tree/description/
 *
 * algorithms
 * Easy (56.65%)
 * Likes:    147
 * Dislikes: 0
 * Total Accepted:    8.4K
 * Total Submissions: 14.8K
 * Testcase Example:  '[5,2,13]'
 *
 * 给定一个二叉搜索树(Binary Search Tree),把它转换成为累加树(Greater
 * Tree),使得每个节点的值是原来的节点值加上所有大于它的节点值之和。
 * 
 * 例如:
 * 
 * 
 * 输入: 二叉搜索树:
 * ⁠             5
 * ⁠           /   \
 * ⁠          2     13
 * 
 * 输出: 转换为累加树:
 * ⁠            18
 * ⁠           /   \
 * ⁠         20     13
 * 
 * 
 */
/**
 * Definition for a binary tree node.
 * type TreeNode struct {
 *     Val int
 *     Left *TreeNode
 *     Right *TreeNode
 * }
 */



 func convertBST(root *TreeNode) *TreeNode {
 var sum  = 0
var  travel func(root *TreeNode) 
 travel = func(root *TreeNode) {
	if root == nil {
		return 
	}
	travel(root.Right)
	sum += root.Val
	root.Val = sum
	travel(root.Left)
	return 
}
 travel(root )
 return root
}