5.4.5 Binary Tree Maximum Path Sum

来源:互联网 发布:少儿编程培训班 编辑:程序博客网 时间:2024/05/19 10:16

原题链接:https://oj.leetcode.com/problems/binary-tree-maximum-path-sum/

The difficulty lies in that each path does not necessarily start with root. 

分析的最好的这篇:http://blog.csdn.net/linhuanmars/article/details/22969069

在这里,函数的返回值定义为以自己为根的一条从根到子结点的最长路径(这里路径就不是当成无向图了,必须往单方向走)。这个返回值是为了提供给它的父结点计算自身的最长路径用,而结点自身的最长路径(也就是可以从左到右那种)则只需计算然后更新即可。这样一来,一个结点自身的最长路径就是它的左子树返回值(如果大于0的话),加上右子树的返回值(如果大于0的话),再加上自己的值。而返回值则是自己的值加上左子树返回值,右子树返回值或者0(注意这里是“或者”,而不是“加上”,因为返回值只取一支的路径和)。”

Time: O(n), Space: O(logn)

public class Solution {    public int maxPathSum(TreeNode root) {        int[] max = new int[1];        max[0] = Integer.MIN_VALUE;        helper(root, max);        return max[0];    }        private int helper(TreeNode root, int[] max){        if(root == null) return 0;        int left = helper(root.left, max);        int right = helper(root.right, max);        int cur = root.val + (left > 0 ? left : 0) + (right > 0 ? right : 0);        if(cur > max[0]) max[0] = cur;        return root.val + Math.max(Math.max(left, right), 0);    }}


0 0