Skip to content

Commit d0fc9c1

Browse files
Create convert-BST-to-greater-tree.java
1 parent 47d087e commit d0fc9c1

File tree

1 file changed

+8
-10
lines changed

1 file changed

+8
-10
lines changed

convert-BST-to-greater-tree.java

Lines changed: 8 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -12,21 +12,19 @@
1212
8 13
1313
/ \ / \
1414
5 9 12 15
15+
It is reversed inorder traversal
1516
*/
1617
public class Solution {
17-
public void convertBST1(TreeNode root) {
18+
int sum = 0;
19+
public TreeNode convert(TreeNode root) {
1820
if (root == null) return;
19-
TreeNode cur = root.right;
20-
while (cur != null) {
21-
convertBST1(cur);
22-
root.val += cur.val;
23-
cur = cur.left;
24-
}
25-
21+
convert(root.right);
22+
sum += cur.val;
23+
cur.val = sum;
24+
convert(root.left);
2625
}
2726
public TreeNode convertBST(TreeNode root) {
28-
convertBST1(root);
29-
convertBST1(root.left);
27+
convert(root);
3028
return root;
3129
}
3230
}

0 commit comments

Comments
 (0)