二叉树的最大路径和
题目描述:
路径 被定义为一条从树中任意节点出发,沿父节点-子节点连接,达到任意节点的序列。同一个节点在一条路径序列中 至多出现一次 。该路径 至少包含一个 节点,且不一定经过根节点。
路径和 是路径中各节点值的总和。
给你一个二叉树的根节点 root ,返回其 最大路径和 。
思路:
寻找最大路径,这条路径要么经过根节点,要么不经过根节点,
(1)如果经过,那就是寻找自根节点往左拓展,找到和(不含根节点)最大的路径,然后自根节点往右拓展和最大的单向路径,最后左边路径和加上右边路径和加上根节点的value。
这个寻找单向路径可以使用递归来求:fun(TreeNode2 root)表示自root向下寻到的最大路径,那他就等于fun(root.left)与fun(root.right)中更大值加上它本身。如果fun(node)<0,可以直接返回0,告诉它的上一级节点,这条路径往下路径总和小于0,可以舍弃
(2)如果不经过根节点,那就变成求maxPathSum(root.left)与maxPathSum( root.right)中的更大值,递归调用自身即可
代码:
public static int maxPathSum(TreeNode2 root) {
if(root==null)return 0;
if(root.left==null&&root.right==null)return root.val;
int lmax = maxPathSum(root.left);
int rmax = maxPathSum(root.right);
int lfun = Math.max(fun(root.left),0);
int rfun = Math.max(fun(root.right),0);
if(root.left==null){
return Math.max(
rmax,
lfun+rfun+root.val
);
}
if(root.right==null){
return Math.max(
lmax,
lfun+rfun+root.val
);
}
return Math.max(
Math.max(lmax,rmax),
lfun+rfun+root.val
);
}
public static int fun(TreeNode2 root){
if(root==null)return 0;
int l = fun(root.left);
int r = fun(root.right);
if(l<=0&&r<=0)return root.val;
return (root.val+Math.max(l,r))>0?(root.val+Math.max(l,r)):0;
}