forked from neetcode-gh/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path0538-convert-bst-to-greater-tree.java
More file actions
43 lines (37 loc) · 977 Bytes
/
0538-convert-bst-to-greater-tree.java
File metadata and controls
43 lines (37 loc) · 977 Bytes
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
// Recursive solution
class Solution {
private int curSum = 0;
public TreeNode convertBST(TreeNode root) {
convertBSTRecursive(root);
return root;
}
private void convertBSTRecursive(TreeNode node) {
if (node == null) {
return;
}
convertBSTRecursive(node.right);
int temp = node.val;
node.val += curSum;
curSum += temp;
convertBSTRecursive(node.left);
}
}
// Iterative solution
class Solution {
public TreeNode convertBST(TreeNode root) {
Stack<TreeNode> stack = new Stack<>();
TreeNode cur = root;
int curSum = 0;
while (cur != null || !stack.isEmpty()) {
while (cur != null) {
stack.push(cur);
cur = cur.right;
}
cur = stack.pop();
cur.val += curSum;
curSum = cur.val;
cur = cur.left;
}
return root;
}
}