124. Binary Tree Maximum Path Sum
阿新 • • 發佈:2020-10-04
問題:
求出給定二叉樹中,最大路徑。(至少包含樹中一個節點)
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: 42
解法:Binary Tree(二叉樹)
由於本問題要利用遞迴求解,
那麼遞迴中,必定含有一個聯絡上下文的變數root,
我們定義遞迴函式為,包含root節點為止,的最大path。
那麼該遞迴函式help有以下特性
1. 包含當前root節點
2. 只包含左右子樹之一 or 兩者都不包含。(最大path:若兩子樹都包含,那麼在上層呼叫中,解只有 root+兩個子樹,無法向上傳遞,做出選擇)
而我們利用help遞迴,要得到的真正的解為:
- 假設使用help求得了,左子樹,右子樹的最大路徑
- l = help(root->left)
- r =help(root->right)
- 對樹中每個節點:
- MAX{
- 只選擇root
- 選擇root+左子樹
- 選擇root+右子樹
- 選擇root+左子樹+右子樹
- }
即:
res = max(res,
root + max(l, 0) + max(r, 0)
)
對於遞迴函式help:
- DEF:
- 包含root的,最大單側子樹路徑。
- STAT:
- root
- OPT:得到遞迴解 l 和 r
- return max(root+l, root+r)
- BASE:
- if root==null, then return 0
程式碼參考:
1 /** 2 * Definition for a binary tree node. 3 * struct TreeNode { 4 * int val; 5 * TreeNode *left; 6 * TreeNode *right; 7 * TreeNode() : val(0), left(nullptr), right(nullptr) {}8 * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} 9 * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} 10 * }; 11 */ 12 class Solution { 13 public: 14 // RECURSION: 15 //DEF: fun help(root): 16 // get the max path of one side, through current root node: 17 // [As a child res] of the whole question. 18 // (we need transfer this res to the upper question) 19 // 1. contains the current root node. 20 // 2. only contains one side child of this root node, or neither to choose(only root). 21 // = root->val + MAX { 22 // left child, 23 // right child, 24 // 0 25 // } 26 //STAT: root 27 //OPT: 28 // return root+ l or r(max) 29 //BASE: 30 // if root==null then: return 0; 31 // 32 // REAL ANS: 33 // for each node, we need calculate: 34 // ans = max(ans, 35 // root 36 // + max{help(root->left), 0} 37 // + max{help(root->right), 0} 38 // ) 39 40 int help(TreeNode* root, int& res) { 41 if(!root) return 0; 42 int l = max(0, help(root->left, res)); 43 int r = max(0, help(root->right, res)); 44 res = max(res, root->val + l + r);// real answer: root+l and r 45 return root->val + max(l, r);// recursion answer: root+l or r 46 } 47 int maxPathSum(TreeNode* root) { 48 if(!root) return 0; 49 int res = INT_MIN; 50 help(root, res); 51 return res; 52 } 53 };