Maximum sum of path in Binary Tree


  • 0
    C
    public class Solution {
       int INVALID = -10000;
        int max;
        public int maxPathSum(TreeNode root) {
        
        max = INVALID;
        if (root==null) return 0;
        int ret = calculateSum(root);
        
        if (ret > max) max= ret;
        return max;
    }
    
    public int calculateSum(TreeNode root) {
        
        if(root == null) return 0;
        
        int leftTreeSum = calculateSum(root.left);
        int rightTreeSum = calculateSum(root.right);
        int currentSum = root.val;
        int currentPathSum = Math.max(currentSum , Math.max(leftTreeSum + currentSum, rightTreeSum + currentSum ));
        max = Math.max(max,Math.max(currentPathSum, leftTreeSum+ rightTreeSum + currentSum));
        
        return currentPathSum;
    } 
    

    }


Log in to reply
 

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