LeetCode-124:Binary Tree Maximum Path Sum (二叉樹最大路徑和)

題目:

Given a non-empty binary tree, find the maximum path sum.

For this problem, a path is defined as any sequence of nodes from some starting node to any node in the tree along the parent-child connections. The path must contain at least one node and does not need to go through the root.

Note:

  • The solution set must not contain duplicate quadruplets.

例子:

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

問題解析:

給二叉樹,尋找二叉樹中從一個節點到任意一個節點的路徑和的最大值。

鏈接:

思路標籤

算法:遞歸DFS

解答:

  • 我們以遞歸的思想,深度優先,從下到上尋找最大的路徑和;
  • 對於每個節點可以與其左右節點相結合,但是當每個根結點作爲左(右)子節點返回時,只能選擇該根根結點和其左右子節點中的最大的一個。(這樣才能稱爲路徑)
/**
 * 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 maxPathSum(TreeNode* root) {
        int maxSum = INT_MIN;
        dfsMaxPath(root, maxSum);
        return maxSum;
    }

    int dfsMaxPath(TreeNode* root, int &maxSum){
        if(!root) return 0;
        int l = max(0, dfsMaxPath(root->left, maxSum));
        int r = max(0, dfsMaxPath(root->right, maxSum));
        maxSum = max(maxSum, l+r+root->val);
        return root->val + max(l,r);
    }
};
發佈了200 篇原創文章 · 獲贊 740 · 訪問量 69萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章