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
- 5.4.5 Binary Tree Maximum Path Sum
- Binary Tree Maximum Path Sum
- Binary Tree Maximum Path Sum
- Binary Tree Maximum Path Sum
- Binary Tree Maximum Path Sum
- Binary Tree Maximum Path Sum
- Binary Tree Maximum Path Sum
- Binary Tree Maximum Path Sum
- Binary Tree Maximum Path Sum
- Binary Tree Maximum Path Sum
- Binary Tree Maximum Path Sum
- Binary Tree Maximum Path Sum
- Binary Tree Maximum Path Sum
- Binary Tree Maximum Path Sum
- Binary Tree Maximum Path Sum
- Binary Tree Maximum Path Sum
- Binary Tree Maximum Path Sum
- Binary Tree Maximum Path Sum
- 打印给定年月的日历
- 扩展欧几里德定理
- 网曝那英携女现身加拿大 破天后涉毒传闻
- HDU 1059 Dividing(一维背包)
- 导航控件2
- 5.4.5 Binary Tree Maximum Path Sum
- poj 1177 矩形并的周长
- linux使用移动硬盘
- 【足迹C++primer】46、动态存储类
- K&R The C Programming language 2
- 字符指针与字符数组
- 循环结构
- 先有鸡还是先有蛋?先有操作系统,还是先有汇编器?(对计算机本质的探讨)
- 自主性学习,用实践开路