题:https://leetcode.com/problems/binary-tree-maximum-path-sum/description/
#题目
Given a non-empty 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 must contain at least one node and does not need to go through the root.
Example 1:
Input: [1,2,3]
1
/ \
2 3
Output: 6
Example 2:
Input: [-10,9,20,null,null,15,7]
-10
/
9 20
/
15 7
Output: 42
思路
该类问题往往都需要往动态规划上面靠,写出状态转移方程。
在这个问题中,最重要的是 求解的量,不是状态转移方程所需要的结果。它只是结果的一部分。
也算是 动态规划,是以 递归的方式
递归的状态:int childSum(TreeNode root) :该结点且向左或右子树延长后的 最大PathSum。
递归初始条件 :
if(root == null)
return 0;
递归转移方程:
int lchildSum = childSum(root.left);
int rchildSum = childSum(root.right);
该访问根的子树 最大pathSum,若子树为负数,那么就舍弃。
int curMaxPathSum = Math.max(0,lchildSum) + Math.max(0,rchildSum) + root.val;
iMaxPathSum =Math.max(iMaxPathSum,curMaxPathSum);
则递归转移为:
左右 子孩子的 childSum 中 较大的那个 ,且大于0,再加上 当前 结点数。
return Math.max(0,Math.max(lchildSum,rchildSum)) + root.val;
code
python
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def getPathSum(self,root):
if root == None:
return 0
left = max(0,self.getPathSum(root.left))
right = max(0,self.getPathSum(root.right))
nodeSum = left+right+root.val
if nodeSum > self.maxSum:
self.maxSum = nodeSum
return max(left,right)+root.val
def maxPathSum(self, root):
"""
:type root: TreeNode
:rtype: int
"""
if root == None:
return 0
self.maxSum = root.val
self.getPathSum(root)
return self.maxSum
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
int iMaxPathSum = Integer.MIN_VALUE;
public int childSum(TreeNode root){
if(root == null)
return 0;
int lchildSum = childSum(root.left);
int rchildSum = childSum(root.right);
int curMaxPathSum = Math.max(0,lchildSum) + Math.max(0,rchildSum) + root.val;
iMaxPathSum =Math.max(iMaxPathSum,curMaxPathSum);
return Math.max(0,Math.max(lchildSum,rchildSum)) + root.val;
}
public int maxPathSum(TreeNode root) {
childSum(root);
return iMaxPathSum;
}
}