Given a binary tree, find the maximum path sum.
The path may start and end at any node in the tree.
For example:
Given the below binary tree,
1 / 2 3
Return 6
.
注意: The path may start and end at any node in the tree. 而不是从叶子到叶子, 所以有很多种情况。
根本的考虑是递归, tree的结构首先考虑递归。
这里从最下面一层开始一层层往上走,直到root。查看每一层的max的值。
每一个root有两边,left and right, 分别查这两边的最值,然后比较,返回的是经过这个node的路径的最大值。
1 /** 2 * Definition for binary tree 3 * public class TreeNode { 4 * int val; 5 * TreeNode left; 6 * TreeNode right; 7 * TreeNode(int x) { val = x; } 8 * } 9 */ 10 public class Solution { 11 int max; 12 public int maxPathSum(TreeNode root) { 13 // Start typing your Java solution below 14 // DO NOT write main() function 15 max = root.val; 16 if(root.right == null && root.left == null) return root.val; 17 PathForNode(root); 18 return max; 19 } 20 public int PathForNode(TreeNode n){ 21 if(n == null) return 0; 22 else{ 23 int right = PathForNode(n.right); 24 int left = PathForNode(n.left); 25 if(max < n.val + right + left) max = n.val + right + left; 26 else if(max < n.val + left) max = n.val + left; 27 else if(max < n.val + right) max = n.val + right; 28 else if(max < n.val) max = n.val; 29 return max(n.val + right , n.val + left,n.val); 30 } 31 } 32 public int max(int a,int b,int c){ 33 if(a < 0 && b < 0 && c < 0) return 0; 34 int s = (a < b) ? b : a; 35 return (s < c) ? c : s; 36 } 37 }
第二遍:
1 /** 2 * Definition for binary tree 3 * public class TreeNode { 4 * int val; 5 * TreeNode left; 6 * TreeNode right; 7 * TreeNode(int x) { val = x; } 8 * } 9 */ 10 public class Solution { 11 int result = Integer.MIN_VALUE; 12 public int maxPathSum(TreeNode root) { 13 // IMPORTANT: Please reset any member data you declared, as 14 // the same Solution instance will be reused for each test case. 15 result = Integer.MIN_VALUE; 16 dfs(root); 17 return result; 18 } 19 public int dfs(TreeNode root){ 20 if(root == null) return 0; 21 int left = dfs(root.left); 22 int right = dfs(root.right); 23 result = Math.max(result, left + right + root.val); 24 return Math.max(0, Math.max(left, right) + root.val);// 不返回小于0的数字!!! 25 } 26 }