Given a non-empty 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 must contain at least one node and does not need to go through the root.
Example 1:
Input: [1,2,3]
1
/ \
2 3
Output: 6
Example 2:
Input: [-10,9,20,null,null,15,7]
-10
/ \
9 20
/ \
15 7
Output: 42
- Method1:递归
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
private int result = Integer.MIN_VALUE;
public int maxPathSum(TreeNode root){
maxSum(root);
return result;
}
public int maxSum(TreeNode root){
if(root == null) return 0;
int leftSum = maxSum(root.left);
int rightSum = maxSum(root.right);
int cur = root.val;
int res = cur + ((leftSum > 0) ? leftSum:0) + ((rightSum > 0) ? rightSum:0); //包括当前节点的树的最大值。
this.result = Math.max(result, res);
return Math.max(cur, Math.max(cur + leftSum, cur + rightSum)); //返回到上一层的可能性有三种, 只返回当前结点,左结点往上, 右结点往上。
}
}
- Method 1: Recursion
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ class Solution { private int max = Integer.MIN_VALUE; public int maxPathSum(TreeNode root) { return Math.max(max(root), this.max); } private int max(TreeNode node){ if(node == null) return 0; int left = Math.max(max(node.left), 0); int right = Math.max(max(node.right), 0); int res = Math.max(node.val, node.val + left + right); this.max = Math.max(max, res); return Math.max(node.val, Math.max(node.val + left, node.val + right)); } }
- Method 1: dfs + traversal 2 childs and return one
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ class Solution { private int result = Integer.MIN_VALUE; public int maxPathSum(TreeNode root) { dfs(root); return this.result; } private int dfs(TreeNode root){ if(root == null) return 0; int left = Math.max(dfs(root.left), 0); int right = Math.max(dfs(root.right), 0); int res = Math.max(root.val, left + right + root.val); this.result = Math.max(result, res); return Math.max(Math.max(left, right) + root.val, root.val); } }