LeetCode: Binary Tree Maximum Path Sum 解題報告


Binary Tree Maximum Path Sum
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

SOLUTION 1:

計算樹的最長path有2種情況:

1. 通過根的path.

  (1)如果左子樹從左樹根到任何一個Node的path大於零,可以鏈到root上

  (2)如果右子樹從右樹根到任何一個Node的path大於零,可以鏈到root上

2. 不通過根的path. 這個可以取左子樹及右子樹的path的最大值。

所以創建一個inner class:

記錄2個值:

1. 本樹的最大path。

2. 本樹從根節點出發到任何一個節點的最大path.

注意,當root == null,以上2個值都要置為Integer_MIN_VALUE; 因為沒有節點可取的時候,是不存在solution的。以免干擾遞歸的計算

 1 /**
 2  * Definition for binary tree
 3  * public class TreeNode {
 4  *     int val;
 5  *     TreeNode left;
 6  *     TreeNode right;
 7  *     TreeNode(int x) { val = x; }
 8  * }
 9  */
10 public class Solution {
11     public class ReturnType {
12         int maxSingle;
13         int max;
14         ReturnType (int maxSingle, int max) {
15             this.max = max;
16             this.maxSingle = maxSingle;
17         }
18     }
19     
20     public int maxPathSum(TreeNode root) {
21         return dfs(root).max;        
22     }
23     
24     public ReturnType dfs(TreeNode root) {
25         ReturnType ret = new ReturnType(Integer.MIN_VALUE, Integer.MIN_VALUE);
26         if (root == null) {
27             return ret;
28         }
29         
30         ReturnType left = dfs(root.left);
31         ReturnType right = dfs(root.right);
32         
33         int cross = root.val;
34         
35         // if any of the path of left and right is below 0, don't add it.
36         cross += Math.max(0, left.maxSingle);
37         cross += Math.max(0, right.maxSingle);
38         
39         // 注意,這里不可以把Math.max(left.maxSingle, right.maxSingle) 與root.val加起來,
40         // 會有可能越界!
41         int maxSingle = Math.max(left.maxSingle, right.maxSingle);
42         
43         // may left.maxSingle and right.maxSingle are below 0
44         maxSingle = Math.max(maxSingle, 0);
45         maxSingle += root.val;
46         
47         ret.maxSingle = maxSingle;
48         ret.max = Math.max(right.max, left.max);
49         ret.max = Math.max(ret.max, cross);
50         
51         return ret;
52     }
53 }
View Code

 

GITHUB:

https://github.com/yuzhangcmu/LeetCode_algorithm/blob/master/tree/MaxPathSum.java


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM