File tree Expand file tree Collapse file tree 1 file changed +50
-0
lines changed Expand file tree Collapse file tree 1 file changed +50
-0
lines changed Original file line number Diff line number Diff line change
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
+ } */
You can’t perform that action at this time.
0 commit comments