File tree 4 files changed +58
-4
lines changed
0500-0599/0538.Convert BST to Greater Tree
1000-1099/1038.Binary Search Tree to Greater Sum Tree
4 files changed +58
-4
lines changed Original file line number Diff line number Diff line change 77
77
<!-- 这里可写当前语言的特殊实现逻辑 -->
78
78
79
79
``` java
80
-
80
+ class Solution {
81
+ int add = 0 ;
82
+ public TreeNode convertBST (TreeNode root ) {
83
+ if (root != null ) {
84
+ convertBST(root. right);
85
+ root. val += add;
86
+ add = root. val;
87
+ convertBST(root. left);
88
+ }
89
+ return root;
90
+ }
91
+ }
81
92
```
82
93
83
94
### ** ...**
Original file line number Diff line number Diff line change 108
108
### ** Java**
109
109
110
110
``` java
111
-
111
+ class Solution {
112
+ int add = 0 ;
113
+ public TreeNode convertBST (TreeNode root ) {
114
+ if (root != null ) {
115
+ convertBST(root. right);
116
+ root. val += add;
117
+ add = root. val;
118
+ convertBST(root. left);
119
+ }
120
+ return root;
121
+ }
122
+ }
112
123
```
113
124
114
125
### ** ...**
Original file line number Diff line number Diff line change 77
77
<!-- 这里可写当前语言的特殊实现逻辑 -->
78
78
79
79
``` java
80
-
80
+ class Solution {
81
+ private int max = 0 ;
82
+
83
+ public TreeNode bstToGst (TreeNode root ) {
84
+ if (root == null ) return new TreeNode (0 );
85
+ int temp = bstToGst(root. right). val;
86
+ root. val += (temp > max ? temp : max);
87
+ max = root. val > max ? root. val : max;
88
+ if (root. left != null ) {
89
+ int temp2 = bstToGst(root. left. right). val;
90
+ root. left. val += max > temp2 ? max : temp2;
91
+ max = max > root. left. val ? max : root. left. val;
92
+ bstToGst(root. left. left);
93
+ }
94
+ return root;
95
+ }
96
+ }
81
97
```
82
98
83
99
### ** ...**
Original file line number Diff line number Diff line change 108
108
### ** Java**
109
109
110
110
``` java
111
-
111
+ class Solution {
112
+ private int max = 0 ;
113
+
114
+ public TreeNode bstToGst (TreeNode root ) {
115
+ if (root == null ) return new TreeNode (0 );
116
+ int temp = bstToGst(root. right). val;
117
+ root. val += (temp > max ? temp : max);
118
+ max = root. val > max ? root. val : max;
119
+ if (root. left != null ) {
120
+ int temp2 = bstToGst(root. left. right). val;
121
+ root. left. val += max > temp2 ? max : temp2;
122
+ max = max > root. left. val ? max : root. left. val;
123
+ bstToGst(root. left. left);
124
+ }
125
+ return root;
126
+ }
127
+ }
112
128
```
113
129
114
130
### ** ...**
You can’t perform that action at this time.
0 commit comments