给出一棵二叉树,寻找一条路径使其路径和最大,路径可以在任一节点中开始和结束(路径和为两个节点之间所在路径上的节点权值之和)
样例
给出一棵二叉树:
1
/ \
2 3
返回 6
一刷没ac
/**
* 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.
*/
public int max ;
public int maxPathSum(TreeNode root) {
max = Integer.MIN_VALUE;
if(root == null) return 0;
maxpath(root);
return max;
}
public int maxpath(TreeNode root){
if(root == null) return 0;
int left = 0, right = 0;
if(root.left != null) left = Math.max(0, maxpath(root.left));
if(root.right != null) right = Math.max(0, maxpath(root.right));
max = Math.max(max, left + right + root.val);
return Math.max(left, right) + root.val;
}
}