有关于我
我的生活
这个网站
刷题之旅
Binary Tree Maximum Path Sum
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: 42Solution: /** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode() {} * TreeNode(int val) { this.val = val; } * TreeNode(int val, TreeNode left, TreeNode right) { * this.val = val; * this.left = left; * this.right = right; * } * } */ class Solution { public int maxPathSum(TreeNode root) { if (root == null) return Integer.MIN_VALUE; int[] max = new int[]{root.val}; dfs(root, max); return max[0]; } private int dfs(TreeNode root, int[] max) { if (root == null) { return Integer.MIN_VALUE; } int left = Math.max(dfs(root.left, max), 0); int right = Math.max(dfs(root.right, max), 0); max[0] = Math.max(max[0], left + root.val + right); return Math.max(left + root.val, right + root.val); } }
Please enable JavaScript to view the comments