Binary Tree Maximum Path Sum

来源:互联网 发布:网络黑侠现在在哪写书 编辑:程序博客网 时间:2024/05/19 20:19

Binary Tree Maximum Path Sum

 

Given a binary tree, find the maximum path sum.

The path may start and end at any node in the tree.

For example:
Given the below binary tree,

       1      / \     2   3

Return 6.

/** * Definition for a binary tree node. * public class TreeNode { *     int val; *     TreeNode left; *     TreeNode right; *     TreeNode(int x) { val = x; } * } */public class Solution {    private int maxSum;    public int maxPathSum(TreeNode root) {                maxSum = Integer.MIN_VALUE;        findMax(root);        return maxSum;    }        private int findMax(TreeNode p) {        if (p == null)            return 0;                    int left = findMax(p.left);        int right = findMax(p.right);                maxSum = Math.max(maxSum, left + right + p.val);        int ret = Math.max(left, right) + p.val;                return ret > 0 ? ret:0;    }}


0 0