您的位置:首页 > 其它

Problem Binary Tree Maximum Path Sum

2014-06-29 14:56 309 查看
Problem Description:

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
.

Solution:

public class Solution {
public int max;
public int maxPathSum(TreeNode root) {
if (root == null) return 0;
max = root.val;
findMax(root);
return max;
}
public  int findMax(TreeNode node) {
if (node == null) return 0;

int left = Math.max(findMax(node.left), 0);
int right = Math.max(findMax(node.right), 0);

max = Math.max(node.val + left + right, max);

return node.val + Math.max(left, right);
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: