您的位置:首页 > 其它

Leetcode: Binary Tree Maximum Path Sum

2013-07-16 05:32 417 查看
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
.

Pay attention to this one.

/**
* Definition for binary tree
* public class TreeNode {
*     int val;
*     TreeNode left;
*     TreeNode right;
*     TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public int max;
public int maxPathSum(TreeNode root) {
// Start typing your Java solution below
// DO NOT write main() function
if(root == null)
return 0;
max = Integer.MIN_VALUE;
get(root);
return max;
}

public int get(TreeNode root){
if(root == null)
return 0;
int left = get(root.left);
int right = get(root.right);
if(left + right + root.val > max)
max = left + right + root.val;
int temp = Math.max(left, right);
return temp + root.val > 0 ? temp + root.val : 0;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: