详细见:leetcode.com/problems/binary-tree-maximum-path-sum
Java Solution: github
package leetcode;
import tools.TreeNode辅助.TreeNode;
/*
Given a binary tree, find the maximum path sum.
For this problem, a path is defined as any sequence of nodes
from some starting node to any node in the tree
along the parent-child connections.
The path does not need to go through the root.
For example:
Given the below binary tree,
1
/ \
2 3
Return 6.
*/
/**
* @author zxwtry
* @email zxwtry@qq.com
* @project OJ
* @package leetcode
* @file P124_BinaryTreeMaximumPathSum.java
* @type P124_BinaryTreeMaximumPathSum
* @date 2017年5月7日 下午10:02:15
* @details Solution: AC 3ms 19.84%
*/
public class P124_BinaryTreeMaximumPathSum {
static class Solution {
public int maxPathSum(TreeNode root) {
if (root == null) return 0;
int[] ans = {Integer.MIN_VALUE};
search(root, ans);
return ans[0];
}
private int search(TreeNode root, int[] ans) {
if (root == null) return 0;
int lv = Math.max(0, search(root.left, ans));
int rv = Math.max(0, search(root.right, ans));
ans[0] = Math.max(ans[0], lv+rv+root.val);
return Math.max(lv, rv) + root.val;
}
}
}
C Solution: github
/*
url: leetcode.com/problems/binary-tree-maximum-path-sum
AC 15ms 59.26%
*/
#include <stdio.h>
#include <stdlib.h>
#include <limits.h>
struct TreeNode {
int val;
struct TreeNode *left;
struct TreeNode *right;
};
typedef struct TreeNode stn;
typedef struct TreeNode * ptn;
int _max(int a, int b) {
return a < b ? b : a;
}
int search(ptn n, int* m) {
int lv = 0, rv = 0;
if (n == NULL) return 0;
lv = search(n->left, m);
rv = search(n->right, m);
*m = _max(*m, lv + rv + n->val);
return _max(_max(_max(lv, rv), 0) + n->val, 0);
}
int maxPathSum(ptn n) {
int m = INT_MIN;
if (n == NULL) return 0;
search(n, &m);
return m;
}
Python Solution: github
#coding=utf-8
'''
url: leetcode.com/problems/binary-tree-maximum-path-sum
@author: zxwtry
@email: zxwtry@qq.com
@date: 2017年5月10日
@details: Solution: 222ms 16.58%
'''
class TreeNode(object):
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution(object):
def search(self, n, ans):
if n == None: return 0
lv = max(self.search(n.left, ans), 0)
rv = max(self.search(n.right, ans), 0)
ans[0] = max(ans[0], lv+rv+n.val)
return max(lv, rv) + n.val
def maxPathSum(self, n):
"""
:type n: TreeNode
:rtype: int
"""
ans = [-(1 << 31)]
self.search(n, ans)
return 0 if n == None else ans[0]
if __name__ == "__main__":
t0 = TreeNode(-1)
print(Solution().maxPathSum(t0))
print(Solution().maxPathSum(None))