LeetCode - Binary Tree Maximum Path Sum
2015-04-16 00:23
363 查看
https://leetcode.com/problems/binary-tree-maximum-path-sum/
这道题可以用递归做,首先,应该有一个全局变量来保存当前遇到的最大path值。
对于每个节点而言,经过它的最大path值,应该是左边的最大path加右边的最大path加自己,如果左边或者右边的最大path是负数,那么就不加这一部分。
另外,对于这个节点的父节点而言,经过父节点的path不可能同时经过这个节点的左右子树,只能经过这个节点的左子树或者右子树,因此这个节点返回给它的父节点的,应该是它单边的最大path
这道题可以用递归做,首先,应该有一个全局变量来保存当前遇到的最大path值。
对于每个节点而言,经过它的最大path值,应该是左边的最大path加右边的最大path加自己,如果左边或者右边的最大path是负数,那么就不加这一部分。
另外,对于这个节点的父节点而言,经过父节点的path不可能同时经过这个节点的左右子树,只能经过这个节点的左子树或者右子树,因此这个节点返回给它的父节点的,应该是它单边的最大path
public class Solution { public int maxPathSum(TreeNode root) { int[] max = new int[1]; max[0] = root.val; getMax(root, max); return max[0]; } public int getMax(TreeNode root, int[] max){ if(root==null) return 0; int left = getMax(root.left, max); int right = getMax(root.right, max); if(left<0) left=0; if(right<0) right = 0; int localMax = root.val+left+right; if(localMax>max[0]) max[0] = localMax; return Math.max(root.val+left, root.val+right); } }
相关文章推荐
- [LeetCode] Binary Tree Maximum Path Sum(最大路径和)
- [LeetCode]Binary Tree Maximum Path Sum
- [LeetCode] Binary Tree Maximum Path Sum Solution
- LeetCode Binary Tree Maximum Path Sum
- Leetcode #124 Binary Tree Maximum Path Sum
- Leetcode Maximum SubArray & Binary Tree Maximum Path Sum
- Binary Tree Maximum Path Sum [leetcode] dp
- LeetCode 124: Binary Tree Maximum Path Sum
- [leetcode]Binary Tree Maximum Path Sum
- LeetCode - Binary Tree Maximum Path Sum 题解
- LeetCode | Binary Tree Maximum Path Sum(二叉树的路径最大值)
- [leetcode] Binary Tree Maximum Path Sum
- Leetcode - Binary Tree Maximum Path Sum
- *Leetcode_binary-tree-maximum-path-sum (updated c++ and python version)
- 124 Binary Tree Maximum Path Sum [Leetcode]
- 【leetcode】Binary Tree Maximum Path Sum
- LeetCode124—Binary Tree Maximum Path Sum
- LeetCode124:Binary Tree Maximum Path Sum
- Leetcode Binary Tree Maximum Path Sum
- [LeetCode]124 Binary Tree Maximum Path Sum