Binary tree maximum path sum( from root to leaf, path must end at leaf node)

return4. (1->3)

/**

* Definition of TreeNode:

* public class TreeNode {

* public int val;

* public TreeNode left, right;

* public TreeNode(int val) {

* this.val = val;

* this.left = this.right = null;

* }

* }

*/

public class Solution {

public class Solution {
/\*\*

 \* @param root the root of binary tree.

 \* @return an integer

 \*/

public int maxPathSum(TreeNode root) {

    // Write your code here

    if (root == null) {

        return Integer.MIN_VALUE;

    }


    int[] globalMax = {Integer.MIN_VALUE};
    helper(root, globalMax,0);
    return globalMax[0];

}

private void helper(TreeNode root, int[] globalMax, int pathSum) {

    if (root == null) {
        return ;
    }

   pathSum += root.val;

   if(root.left == null && root.right == null) {
       globalMax[0] = Math.max(globalMax[0], pathSum);
   }

   helper(root.left, globalMax, pathSum);
   helper(root.right, globalMax,PathSum);

}
}

results matching ""

    No results matching ""