HELP --- TLE problem


  • 0

    I tried this code but got TLE for the last test case, I think It's a O(n) solution and don't want any global variable, can anyone help to improve or have some advice?
    Thanks!

    public class Solution {
        public int maxPathSum(TreeNode root) {
            if (root == null) {return Integer.MIN_VALUE;}
            
            return Math.max(
                Math.max(maxPathSum(root.left), maxPathSum(root.right)),
                Math.max(0, helper(root.left)) + root.val + Math.max(0, helper(root.right))
                );
        }
        
        public int helper(TreeNode root) {
            if (root == null) {return 0;}
            int r = helper(root.right), l = helper(root.left);
            return root.val + Math.max(0, Math.max(r, l));
        }
    }
    

Log in to reply
 

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