-
Notifications
You must be signed in to change notification settings - Fork 0
/
ConvertBSToGreaterTree.java
65 lines (60 loc) · 1.64 KB
/
ConvertBSToGreaterTree.java
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
public class Solution {
// public TreeNode convertBST(TreeNode root) {
// int sum = getSum(root);
// Inorder(root,sum);
// return root;
// }
// private int getSum(TreeNode root){
// int res = 0;
// if(root.left == null && root.right == null){
// return res + root.val;
// }
// res += root.val;
// if(root.left != null){
// res+=getSum(root.left);
// }
// if(root.right != null){
// res+=getSum(root.rogjt);
// }
// return res;
// }
// private void Inorder(TreeNode root, int sum){
// Inorder(root.left, sum);
// int tmp = root.val;
// root.val = sum;
// sum-=tmp;
// Inorer(root.right,sum);
// }
public TreeNode convertBST(TreeNode root) {
if(root == null || root.left == null && root.right == null){
return root;
}
int[] sum = {getSum(root)};
Inorder(root,sum);
return root;
}
private int getSum(TreeNode root){
int res = 0;
if(root.left == null && root.right == null){
return res + root.val;
}
res += root.val;
if(root.left != null){
res+=getSum(root.left);
}
if(root.right != null){
res+=getSum(root.right);
}
return res;
}
private void Inorder(TreeNode root, int[] sum){
if(root == null){
return;
}
Inorder(root.left, sum);
int tmp = root.val;
root.val = sum[0];
sum[0]-=tmp;
Inorder(root.right,sum);
}
}