您的位置:首页 > 编程语言 > Go语言

Binary Tree Maximum Path Sum

2014-01-29 02:14 316 查看


Binary Tree Maximum Path Sum

 Total Accepted: 5229 Total
Submissions: 27600My Submissions

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
.

关键注意几点:

需要一个global variable 来保存当前为止找到的最大值。

在 DFS 过程中,检查 root > max? || root + left + right > max? || root + max(left,right) > max?, 总之这步要使得max的值更新为目前能找到的最大值。

返回的时候要注意只能返回 root, left+root, right+root 中的最大者。 不能返回 root+left+rigth, 不然就不是一条path, 而是多条了。

/**
* Definition for binary tree
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
int max = Integer.MIN_VALUE;
public int maxPathSum(TreeNode root) {
maxPathSumHelper(root);
return max;
}

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