124. Binary Tree Maximum Path Sum
题目:
Given a binary tree, find the maximum path sum.
For this problem, a path is defined as any sequence of nodes from some starting node to any node in the tree along the parent-child connections. The path does not need to go through the root.
For example:
Given the below binary tree,
1 / \ 2 3
Return 6
.
链接: http://leetcode.com/problems/binary-tree-maximum-path-sum/
题解:
a path被定义为任意starting node通过parent-child link到另一node, 所以我们要考虑左子树和,右子树和以及左右子树和。 需要传递一个数组引用变量,或者定义一个全局变量来传递最终的运算结果。这个也和以前的一些自底向上构建二叉树的题目比较类似,很巧妙。还需要多多研究。
Time Complexity - O(n),Space Complexity - O(n)
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ public class Solution { public int maxPathSum(TreeNode root) { int[] max = {Integer.MIN_VALUE}; int res = maxPathSum(root, max); return max[0]; } private int maxPathSum(TreeNode root, int[] max) { if(root == null) return 0; int left = maxPathSum(root.left, max); int right = maxPathSum(root.right, max); int res = Math.max(root.val, Math.max(root.val + left, root.val + right)); max[0] = Math.max(max[0], Math.max(res, root.val + left + right)); return res; } }
Update:
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ public class Solution { int max = Integer.MIN_VALUE; public int maxPathSum(TreeNode root) { helper(root); return max; } private int helper(TreeNode root) { if(root == null) return 0; int left = Math.max(helper(root.left), 0); int right = Math.max(helper(root.right), 0); max = Math.max(max, root.val + left + right); return root.val + Math.max(left, right); } }
题外话: 今天头比较晕,上午把工作上的事做得差不多了,下午就一直头晕。一天就做了两道题,而且还做得不是那么清楚。是真的老了吗???中午吃了chipotle,晚上去吃了成都23,总的来说还是很疲惫。马上进入11月份,还剩17天假期,怎么使用是个大问题。以前总想着10月份刷题就完成了,然后就是飞来飞去地面试,结果这第一遍还没做到一半,再不抓紧时间,人生真的荒废过去了。 好好刷吧。
Reference:
https://leetcode.com/discuss/43797/elegant-java-solution
https://leetcode.com/discuss/14190/accepted-short-solution-in-java