package leetcode;

/**
 * https://leetcode.com/problems/convert-bst-to-greater-tree/
 */
public class Problem538 {
    public static class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;

        TreeNode(int x) {
            val = x;
        }
    }

    public TreeNode convertBST(TreeNode root) {
        if (root == null) {
            return root;
        }
        return convert(root, new Sum());
    }

    private static class Sum {
        private int val;
    }

    private static TreeNode convert(TreeNode node, Sum sum) {
        if (node.left == null && node.right == null) {
            sum.val += node.val;
            return new TreeNode(sum.val);
        }
        TreeNode right = null;
        if (node.right != null) {
            right = convert(node.right, sum);
        }
        sum.val += node.val;
        int val = sum.val;
        TreeNode left = null;
        if (node.left != null) {
            left = convert(node.left, sum);
        }
        TreeNode parent = new TreeNode(val);
        parent.left = left;
        parent.right = right;
        return parent;
    }
}

@@ -324,71 +324,8 @@
 ) %7B%0A
-        if (root == null) %7B%0A            return root;%0A        %7D%0A
     
@@ -342,16 +342,19 @@
  convert
+BST
 (root, n
@@ -356,19 +356,22 @@
 ot, new 
-Sum
+IntRef
 ());%0A   
@@ -378,71 +378,8 @@
  %7D%0A%0A
-    private static class Sum %7B%0A        private int val;%0A    %7D%0A%0A
     
@@ -409,16 +409,19 @@
  convert
+BST
 (TreeNod
@@ -426,17 +426,20 @@
 ode 
-node, Sum
+root, IntRef
  sum
@@ -458,213 +458,72 @@
 if (
-node.left == null && node.right == null) %7B%0A            sum.val += node.val;%0A            return new TreeNode(sum.val);%0A        %7D%0A        TreeNode right = null;%0A        if (node.right != null) %7B%0A            
+root == null) %7B%0A            return null;%0A        %7D%0A        root.
 righ
@@ -533,21 +533,24 @@
  convert
-(node
+BST(root
 .right, 
@@ -551,34 +551,24 @@
 ight, sum);%0A
-        %7D%0A
         sum.
@@ -574,20 +574,20 @@
 .val += 
-node
+root
 .val;%0A  
@@ -592,20 +592,21 @@
         
-int 
+root.
 val = su
@@ -624,75 +624,13 @@
     
-TreeNode left = null;%0A        if (node.left != null) %7B%0A            
+root.
 left
@@ -643,13 +643,16 @@
 vert
-(node
+BST(root
 .lef
@@ -672,134 +672,85 @@
     
-%7D%0A        TreeNode parent = new TreeNode(val)
+return root
 ;%0A    
+%7D%0A%0A
     p
-arent.left = left;%0A        parent.right = right;%0A        return parent
+rivate static class IntRef %7B%0A        private int val
 ;%0A  

Update problem 538