考虑利用递归求解经过每个点的最大路径...对于节点root来说,经过其的最大路径由max(root.left),max(root.right)和root.val决定....其中root的值必须要考虑,而其余两个值仅在该值大于0的情况下才需要被考虑....这样递归的自底向上求出进过每个点的最长路径并动态更新最大值,即可得到这棵树内的最长路径。
!!!!要注意的是递归返回的并不能是经过该点的最长路径,由于返回值代表的路径需要能够经过该节点的父节点,所以返回路径只能经过左子结点或右子结点中的一个....因而应该返回max of(root.val,root.val+max(root,left),root.val+max(root.right))
/**
* Definition for binary tree
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
int res=Integer.MIN_VALUE;
public int maxPathSum(TreeNode root) {
if(root==null)
{
return res;
}
fun(root);
return res;
}
int fun(TreeNode root)
{
if(root==null)
{
return 0;
}
int val = root.val;
int lv=0,lr=0;
if(root.left!=null)
{
lv = fun(root.left);
if(lv>0)
{
val += lv;
}
}
if(root.right!=null)
{
lr = fun(root.right);
if(lr>0)
{
val += lr;
}
}
if(val>res)
{
res = val;
}
return Math.max(root.val,Math.max(root.val+lv,root.val+lr));
}
}
本文探讨了如何使用递归算法解决在二叉树中寻找经过每个节点的最大路径的问题。通过自底向上的策略,算法动态更新每个节点的最大路径值,最终找到整棵树内的最长路径。
219

被折叠的 条评论
为什么被折叠?



