LeetCode 124 Binary Tree Maximum Path Sum

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.

思路:本人脑子笨。一開始想了好久都木有思路,仅仅有一个笨办法:把全部的叶子i到叶子节点j的路径都遍历一遍。近期写回溯法用递归用的多,我突然想到了递归能够。用一个全局变量max来存储最大值,然后再求最大连续子序列和。如果我们已经知道了某个节点node的左右子树的最大路径和leftmaxsum。rightmaxsum。那么这个节点node的最大路径和为Math.max(node.val,Math.max(node.val+leftmaxsum,node.val+rightmaxsum));这个节点node的最大路径和仅仅是为了给node的父节点准备的,并不是给node自己准备的。

那么给node准备用啥呢---max。        temp=root.val+leftmaxsum+rightmaxsum; max=max>temp?max:temp;  这样max就能返回当前的最大路径和。代码例如以下:

public class Solution {
	static int max = Integer.MIN_VALUE;

	public int maxPathSum(TreeNode root) {
		max = Integer.MIN_VALUE;
		PathSum(root);
		return max;
	}

	public int PathSum(TreeNode root) {
		if(root==null) return 0;
		int leftmaxsum=0;
		int rightmaxsum=0;
		int temp=root.val;
        if(root.left!=null){
        	leftmaxsum=Math.max(PathSum(root.left),0);
        } 
        if(root.right!=null){
        	rightmaxsum=Math.max(PathSum(root.right),0);
        }
        temp=root.val+leftmaxsum+rightmaxsum;
        max=max>temp?max:temp;
        return Math.max(root.val,Math.max(root.val+leftmaxsum, root.val+rightmaxsum));
    }
}


原文地址:https://www.cnblogs.com/jhcelue/p/7323611.html