Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit 1497024

Browse files
author
侯利朋
committed
.\538.convert-bst-to-greater-tree ok
1 parent 3e55d3b commit 1497024

File tree

1 file changed

+46
-0
lines changed

1 file changed

+46
-0
lines changed

538.convert-bst-to-greater-tree.go

Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
/*
2+
* @lc app=leetcode id=538 lang=golang
3+
*
4+
* [538] Convert BST to Greater Tree
5+
*/
6+
/**
7+
* Definition for a binary tree node.
8+
* type TreeNode struct {
9+
* Val int
10+
* Left *TreeNode
11+
* Right *TreeNode
12+
* }
13+
*/
14+
// 188 ms, faster than 86.19%
15+
// [2,0,3,-4,1]
16+
// [1,0,4,-2,null,3]
17+
func convertBST(root *TreeNode) *TreeNode {
18+
return help(root, 0)
19+
}
20+
21+
// 比当前节点大的值是右子树的值,如果该节点在左子树中,再加上父节点的值
22+
func help(root *TreeNode, parent int) *TreeNode {
23+
if root == nil {
24+
return root
25+
}
26+
27+
// help(root.Right, 0) + root.Val?????????
28+
help(root.Right, parent) // 一定注意,右节点的时候传入的是当前节点的父节点,因为左子树的所有节点小于根节点
29+
30+
if root.Right != nil { // 注意,有节点可能为空
31+
// root.Val += root.Right.Val + parent 一定注意,此时的右节点已经加上了parent,不要重复计算
32+
// root.Val += root.Right.Val // parent
33+
// 加上的是右节点的最左节点的值
34+
p := root.Right
35+
for p.Left != nil {
36+
p = p.Left
37+
}
38+
root.Val += p.Val
39+
} else {
40+
root.Val += parent
41+
}
42+
43+
help(root.Left, root.Val)
44+
45+
return root
46+
}

0 commit comments

Comments
 (0)