LeetCode 124. Binary Tree Maximum Path Sum(二叉樹最大路徑和)
阿新 • • 發佈:2019-01-06
Given a 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 does not need to go through the root.
For example:
Given the below binary tree,
1 / \ 2 3
Return 6
.
方法:分治策略,動態規劃。
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ public class Solution { // 這是我根據網上的例子,自己重寫的 private int max; private int maxSideSum(TreeNode root) { if (root == null) return 0; int left = maxSideSum(root.left); int right = maxSideSum(root.right); int v = left + root.val + right; if (v > max) max = v; int sum = root.val; if (root.val+left>sum) sum = root.val+left; if (root.val+right>sum) sum = root.val+right; if (sum>max) max = sum; return sum; } public int maxPathSum(TreeNode root) { if (root == null) return 0; max = root.val; maxSideSum(root); return max; } // 這是網上搜索的解決方案,非常簡潔 // http://www.programcreek.com/2013/02/leetcode-binary-tree-maximum-path-sum-java/ }
更簡潔的版本:
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ public class Solution { private int max = Integer.MIN_VALUE; private int maxSideSum(TreeNode node) { if (node == null) return 0; int left = maxSideSum(node.left); int right = maxSideSum(node.right); max = Math.max(max, left + node.val + right); return Math.max(0, node.val + Math.max(left, right)); } public int maxPathSum(TreeNode root) { maxSideSum(root); return max; } }