[JAVA] inorder dfs / T : O(N), S : O(1)


  • 0
    J
    class Solution {
        public TreeNode convertBST(TreeNode root) {
            convert(root, 0);
            return root;
        }
        
        public int convert(TreeNode root, int rightPValue){
            if(root == null)
                return 0;
            
            int sum = root.val;
            sum += convert(root.right, rightPValue); // rightPValue
            root.val = sum + rightPValue; // Self + rightPValue + rightCValue
            sum += convert(root.left, sum + rightPValue); // sum + rightPValue
            return sum; 
        }
    }
    

Log in to reply
 

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