File tree Expand file tree Collapse file tree 1 file changed +43
-0
lines changed Expand file tree Collapse file tree 1 file changed +43
-0
lines changed Original file line number Diff line number Diff line change
1
+ // Recursive solution
2
+ class Solution {
3
+ private int curSum = 0 ;
4
+
5
+ public TreeNode convertBST (TreeNode root ) {
6
+ convertBSTRecursive (root );
7
+ return root ;
8
+ }
9
+
10
+ private void convertBSTRecursive (TreeNode node ) {
11
+ if (node == null ) {
12
+ return ;
13
+ }
14
+
15
+ convertBSTRecursive (node .right );
16
+ int temp = node .val ;
17
+ node .val += curSum ;
18
+ curSum += temp ;
19
+ convertBSTRecursive (node .left );
20
+ }
21
+ }
22
+
23
+ // Iterative solution
24
+ class Solution {
25
+ public TreeNode convertBST (TreeNode root ) {
26
+ Stack <TreeNode > stack = new Stack <>();
27
+ TreeNode cur = root ;
28
+
29
+ int curSum = 0 ;
30
+ while (cur != null || !stack .isEmpty ()) {
31
+ while (cur != null ) {
32
+ stack .push (cur );
33
+ cur = cur .right ;
34
+ }
35
+ cur = stack .pop ();
36
+ cur .val += curSum ;
37
+ curSum = cur .val ;
38
+ cur = cur .left ;
39
+ }
40
+
41
+ return root ;
42
+ }
43
+ }
You can’t perform that action at this time.
0 commit comments