[LeetCode] 124. 二叉樹中的最大路徑和(深度優先遍歷+記憶數組)

124. 二叉樹中的最大路徑和

給定一個非空二叉樹,返回其最大路徑和。

本題中,路徑被定義爲一條從樹中任意節點出發,達到任意節點的序列。該路徑至少包含一個節點,且不一定經過根節點。

示例 1:

輸入: [1,2,3]

       1
      / \
     2   3

輸出: 6

示例 2:

輸入: [-10,9,20,null,null,15,7]

   -10
   / \
  9  20
    /  \
   15   7

輸出: 42

解題思路: 此題解題的關鍵是,要將最大路徑分離出兩種情況,即以節點出發的最大路徑,和穿過這個節點的最大路徑,然後前者又可以分路徑只包含節點本身和包含節點+若干左(或者右)子樹上的節點。另外爲了減少遍歷過程中的重複計算,因此需要加入記憶數組。

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    int helper(TreeNode* node, unordered_map<TreeNode*, int>& m, int &res) {
        if (!node) return 0;
        if (m.count(node)) {
            res = max(res, m[node]);
            return m[node];
        }
        int left = helper(node->left, m, res);
        int right = helper(node->right, m, res);
        m[node] = max(node->val, max(node->val + left, node->val + right));
        res = max(res, max(m[node], left + right + node->val));
        return m[node];
    }
    int maxPathSum(TreeNode* root) {
        if (!root) return 0;
        unordered_map<TreeNode*, int> m;
        int res = INT_MIN;
        helper(root, m, res);
        return res;
    }
};
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章