標籤:
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.
題意: 求一個二叉樹中任意聯通兩點路徑和的最大值。
思路: 深度遍曆該二叉樹。
具有最大和的路徑有三種情況:
1. 就在root.left子樹中;2. 就在root.right子樹中;3.包含root節點,一部分在root.left中,另一部分在root.right中。
我們記錄兩個資料,全域變數max表示全域的最大值,局部變數currentMax表示經過當前root節點的路徑的最大值。如所示
在以-9為根的子樹中,max=7, currentMax=(-9+7)=-2;
在以3為根節點的子樹中,max=11,currentMax=(6+3)=9;
在以1為根節點的子樹中,max=11, currentMax=(1+9)=10;
最後,我們想要的結果是max;
本題需要注意遞迴方法的傳回值。代碼如下:
1 public int maxPathSum(TreeNode root) { 2 if(root == null) 3 return 0; 4 maxPathSumHelper(root); 5 return this.max; 6 } 7 8 public int max = Integer.MIN_VALUE; 9 public int maxPathSumHelper(TreeNode root) {10 if(root == null)11 return 0;12 int leftMax = 0;13 int rightMax = 0;14 15 int returnValue = root.val;16 max = Math.max(root.val, max);17 if(root.left != null) {18 leftMax = maxPathSumHelper(root.left);19 max = Math.max(max, Math.max(leftMax, leftMax+root.val));20 returnValue = Math.max(returnValue, leftMax+root.val);21 }22 if(root.right != null) {23 rightMax = maxPathSumHelper(root.right);24 max = Math.max(max, Math.max(rightMax, rightMax+root.val));25 returnValue = Math.max(returnValue, rightMax+root.val);26 }27 if(root.left != null && root.right != null) {28 max = Math.max(max, root.val+leftMax+rightMax);29 }30 31 return returnValue;32 }
LeetCode-124 Binary Tree Maximum Path Sum