-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy path538.go
More file actions
49 lines (43 loc) · 996 Bytes
/
538.go
File metadata and controls
49 lines (43 loc) · 996 Bytes
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
/*
* @Time : 2020/9/21 15:39
* @Author : cancan
* @File : 538.go
* @Function : 把二叉搜索树转换为累加树
*/
/*
* 给定一个二叉搜索树(Binary Search Tree),把它转换成为累加树(Greater Tree),使得每个节点的值是原来的节点值加上所有大于它的节点值之和。
*
* 例如:
* 输入: 原始二叉搜索树:
* 5
* / \
* 2 13
*
* 输出: 转换为累加树:
* 18
* / \
* 20 13
*/
package QuestionBank
func convertBST(root *TreeNode) *TreeNode {
l := convertBSTDfs(root)
if len(l) <= 1 {
return root
}
s := l[0].Val
for idx := 1; idx < len(l); idx++ {
s += l[idx].Val
l[idx].Val = s
}
return root
}
func convertBSTDfs(root *TreeNode) []*TreeNode {
ret := []*TreeNode{}
if root == nil {
return ret
}
ret = append(ret, convertBSTDfs(root.Right)...)
ret = append(ret, root)
ret = append(ret, convertBSTDfs(root.Left)...)
return ret
}