A recursive solution for this question based on JAVA

  • 0

    public class Solution {

    public int maxPathSum(TreeNode root) {
        int[] max = new int[]{Integer.MIN_VALUE};
        return Math.max(this.helper(root,max,root.val), max[0]);
    private int helper (TreeNode root, int[] max, int val){
        if (root==null)
            return val <0 ? val : 0;
        int left = helper(root.left, max, val);
        int right = helper(root.right, max, val);
        max[0] = Math.max(Math.max(max[0], Math.max(left, right)), left+root.val+right);
        return Math.max(Math.max(left+root.val, right+root.val),root.val);


Log in to reply

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