LeetCode124 二叉树中的最大路径和(dfs)

LeetCode124 二叉树中的最大路径和

dfs左右子节点的最大收益

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

    def maxPathSum(self, root: TreeNode) -> int:
        def dfs(node):
            if not node:
                return 0

            leftGain = max(dfs(node.left), 0)
            rightGain = max(dfs(node.right), 0)
            
            priceNewpath = node.val + leftGain + rightGain
            self.maxSum = max(self.maxSum, priceNewpath)

            return node.val + max(leftGain, rightGain)
   
        dfs(root)
        return self.maxSum

posted on 2022-06-29 12:54  solvit  阅读(23)  评论(0编辑  收藏  举报

导航