Given a binary tree, find the maximum path sum from root.
The path may end at any node in the tree and contain at least one node in it.
Example
Given the below binary tree:
1
/
2 3
return 4
. (1->3)
1. 从上往下思考的试加法。传入从root到现在节点之前的sum值,试加当前点,检查更新全局变量。分别试着试加左节点,右节点。
2.从下往上思考的分治法。定义函数返回从当前节点向下任意点终结的最大sum值。那么显然返回的应该就是root.val, root.val往左接龙, root.val往右接龙三选一。这里有一个对本题的根本理解对后面进阶改题有帮助:如果左子树的答案是负数,我就嫌弃你不接龙了。因为这种接龙游戏中有一个天然的,自带的选择,就是+0不接。如果你比0都小,那就不要你来拖后腿了。
PS: 遇到顶部出发点固定,但底部终结点不固定的二叉树题目,都可以想想从上往下思考的试加法的!类似的如,不固定起点终点的二叉树向target求和题 http://www.cnblogs.com/jasminemzy/p/7669615.html
1.从上往下思考的试加法
/** * Definition of TreeNode: * public class TreeNode { * public int val; * public TreeNode left, right; * public TreeNode(int val) { * this.val = val; * this.left = this.right = null; * } * } */ public class Solution { /* * @param root: the root of binary tree. * @return: An integer */ private int maxSum = Integer.MIN_VALUE; public int maxPathSum2(TreeNode root) { // write your code here helper(root, 0); return maxSum; } // 尝试加此时节点。 // 如果根固定,儿子末端不固定,那要从上往下走(在参数列表里记录),不好从下往上递归(在返回值里记录) private void helper(TreeNode head, int sum) { if (head == null) { return; } sum += head.val; if (sum > maxSum) { maxSum = sum; } helper(head.left, sum); helper(head.right, sum); return; } }
2.从下往上思考的分治法
public class Solution { /** * @param root the root of binary tree. * @return an integer */ public int maxPathSum2(TreeNode root) { if (root == null) { return Integer.MIN_VALUE; } int left = maxPathSum2(root.left); int right = maxPathSum2(root.right); return root.val + Math.max(0, Math.max(left, right)); } }