File tree Expand file tree Collapse 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 Expand file tree Collapse file tree 4 files changed +58
-4
lines changed Original file line number Diff line number Diff line change 7777<!-- 这里可写当前语言的特殊实现逻辑 -->
7878
7979``` 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+ }
8192```
8293
8394### ** ...**
Original file line number Diff line number Diff line change 108108### ** Java**
109109
110110``` 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+ }
112123```
113124
114125### ** ...**
Original file line number Diff line number Diff line change 7777<!-- 这里可写当前语言的特殊实现逻辑 -->
7878
7979``` 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+ }
8197```
8298
8399### ** ...**
Original file line number Diff line number Diff line change 108108### ** Java**
109109
110110``` 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+ }
112128```
113129
114130### ** ...**
You can’t perform that action at this time.
0 commit comments