描述
给出一棵二叉树,寻找一条路径使其路径和最大,路径可以在任一节点中开始和结束(路径和为两个节点之间所在路径上的节点权值之和)
样例
给出一棵二叉树:
1
/ \
2 3
返回 6
代码
根据后序遍历,从下到上,max用来保存最大值,在maxPath函数中,递归返回左右子树的某个子树的最大值。
/**
* Definition of TreeNode:
* public class TreeNode {
* public int val;
* public TreeNode left, right;
* public TreeNode(int val) {
* this.val = val;
* this.left = this.right = null;
* }
* }
*/
public class Solution {
/**
* @param root: The root of binary tree.
* @return: An integer
*/
int max=Integer.MIN_VALUE;
public int maxPathSum(TreeNode root) {
// write your code here
if(root==null){
return 0;
}
maxPath(root);
return max;
}
private int maxPath(TreeNode root){
if(root==null){
return 0;
}
int left=maxPath(root.left);
int right=maxPath(root.right);
int cur=root.val+(left>0?left:0)+(right>0?right:0);
max=Math.max(max,cur);
return root.val+Math.max(left,right);
}
}