[C++] [Java] Clean Code


  • 0

    C++

    class Solution {
    public:
        TreeNode* convertBST(TreeNode* root) {
            int sum = 0;
            inorder(root, sum);
            return root;
        }
    
    private:
        void inorder(TreeNode* node, int& sum) {
            if (node) {
                inorder(node->right, sum);
                sum += node->val;
                node->val = sum;
                inorder(node->left, sum);
            }
        }
    };
    

    Java

    public class Solution {
        public TreeNode convertBST(TreeNode root) {
            int[] sum = new int[1];
            inorder(root, sum);
            return root;        
        }
    
        private void inorder(TreeNode node, int[] sum) {
            if (node != null) {
                inorder(node.right, sum);
                sum[0] += node.val;
                node.val = sum[0];
                inorder(node.left, sum);
            }
        }
    }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.