比较简单的二叉树题目,一开始以为需要找从叶节点到另一个叶节点的路径的最大值,但题目实际上说start|end可以是任意节点,实现过程稍微有点不一样,不过思路大致是相同的。
题目:
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.
代码实现:
public class Solution {
public int maxPathSum(TreeNode root) {
if(root==null)
return 0;
int[] res=new int[1];
res[0]=Integer.MIN_VALUE;
maxDfs(root,res);
return res[0];
}
private int maxDfs(TreeNode root,int[] res){
int curRootSum=root.val;
int depthMax=0;
int subMax;
if(root.left!=null){
subMax=maxDfs(root.left,res);
if(subMax>0) {
depthMax = Math.max(depthMax,subMax);
curRootSum += subMax;
}
}
if(root.right!=null){
subMax=maxDfs(root.right,res);
if(subMax>0) {
depthMax = Math.max(depthMax,subMax);
curRootSum += subMax;
}
}
res[0]=Math.max(res[0],curRootSum);
return depthMax+root.val;
}
}