Skip to content

Commit 18341e6

Browse files
committed
added convert bst to greater tree
1 parent 5e51b1c commit 18341e6

File tree

1 file changed

+50
-0
lines changed

1 file changed

+50
-0
lines changed

Trees/BSTtoGreaterTree.java

Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
1+
package Trees;
2+
3+
import java.util.Stack;
4+
5+
// LeetCode 538.
6+
public class BSTtoGreaterTree {
7+
static class TreeNode {
8+
int val;
9+
TreeNode left,right;
10+
}
11+
public TreeNode convertBST(TreeNode root) {
12+
13+
int sum = 0;
14+
TreeNode node = root;
15+
Stack<TreeNode> stack = new Stack<>();
16+
17+
while(!stack.isEmpty() || node != null) {
18+
19+
// push all the nodes in the right subtree
20+
while(node != null) {
21+
stack.push(node);
22+
node = node.right;
23+
}
24+
25+
node = stack.pop();
26+
sum += node.val;
27+
node.val = sum;
28+
29+
node = node.left;
30+
31+
}
32+
33+
return root;
34+
}
35+
}
36+
37+
38+
/* Recursive approach
39+
class Solution {
40+
int sum = 0;
41+
public TreeNode convertBST(TreeNode root) {
42+
if(root == null) return null;
43+
44+
convertBST(root.right);
45+
sum = sum + root.val;
46+
root.val = sum;
47+
convertBST(root.left);
48+
return root;
49+
}
50+
} */

0 commit comments

Comments
 (0)