leetcode--124--二叉樹中的最大路徑和

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

本題中,路徑被定義為一條從樹中任意節(jié)點出發(fā),沿父節(jié)點-子節(jié)點連接,達(dá)到任意節(jié)點的序列。該路徑至少包含一個節(jié)點,且不一定經(jīng)過根節(jié)點。

示例 1:

輸入:[1,2,3]

   1
  / \
 2   3

輸出:6
示例 2:

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

-10
/
9 20
/
15 7

輸出:42

鏈接:https://leetcode-cn.com/problems/binary-tree-maximum-path-sum

思路:
1、這道題采用二叉樹的后序遍歷。對于每一個節(jié)點,計算其左右子樹單側(cè)的最大路徑和,通過其左右側(cè)、當(dāng)前節(jié)點的和與之前的最大路徑和進(jìn)行對比,找到當(dāng)前節(jié)點下的最大路徑和。上述過程通過遞歸進(jìn)行完成

Python代碼

import sys

# Definition for a binary tree node.
# class TreeNode(object):
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution(object):

    def __init__(self):
        self.ans = -1*sys.maxint-1

    def singlePathSum(self, root):
        if not root:
            return 0
        left = max(0, self.singlePathSum(root.left))
        right = max(0, self.singlePathSum(root.right))
        self.ans = max(self.ans, root.val+left+right)
        return root.val + max(left, right)  # 單側(cè)下最大路徑


    def maxPathSum(self, root):
        """
        :type root: TreeNode
        :rtype: int
        """
        self.singlePathSum(root)

        return  self.ans
        

C++ 代碼:

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
public:

    int ans = INT_MIN;

    int singlePathSum(TreeNode* root){
        if (root==nullptr) {
            return 0;
        }
        int left = max(0, singlePathSum(root->left));
        int right = max(0, singlePathSum(root->right));
        ans = max(ans, root->val+left+right);
        return root->val+max(left, right);
    }

    int maxPathSum(TreeNode* root) {
        singlePathSum(root);
        return ans;
    }
};
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

友情鏈接更多精彩內(nèi)容