LeetCode-124.二叉樹中的最大路徑和(相關話題:深度優先)
阿新 • • 發佈:2018-12-22
給定一個非空二叉樹,返回其最大路徑和。
本題中,路徑被定義為一條從樹中任意節點出發,達到任意節點的序列。該路徑至少包含一個節點,且不一定經過根節點。
示例 1:
輸入: [1,2,3]
1
/ \
2 3
輸出: 6
示例 2:
輸入: [-10,9,20,null,null,15,7]
-10
/ \
9 20
/ \
15 7
輸出: 42
Java程式碼:
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ class Solution { public int maxSum = Integer.MIN_VALUE; public int maxPathSum(TreeNode root) { if(null == root) return 0; dfs(root); return maxSum; } private int dfs(TreeNode root){ if(null == root) return 0; int curVal = root.val, leftSum = dfs(root.left), rightSum = dfs(root.right); if(0 < leftSum) curVal += leftSum; if(0 < rightSum) curVal += rightSum; maxSum = Math.max(maxSum, curVal); return Math.max(root.val, Math.max(root.val+leftSum, root.val+rightSum)); } }