티스토리 뷰

728x90
반응형

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

 

Binary Tree Maximum Path Sum - LeetCode

Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.

leetcode.com


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

class Solution:
    def __init__(self):
        self.max_val=float('-inf')
        
    def maxPathSum(self, root: TreeNode) -> int:
        def maxPathDown(node):
            if node is None:
                return 0
            left=max(0, maxPathDown(node.left))
            right=max(0, maxPathDown(node.right))
            self.max_val= max(self.max_val, left+right+node.val)
            return max(left,right)+node.val
        
        maxPathDown(root)
        return self.max_val

728x90
반응형

'알고리즘 > LeetCode' 카테고리의 다른 글

[LeetCode-1266] Minimum Time Visiting All Points  (0) 2020.03.18
반응형
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2024/04   »
1 2 3 4 5 6
7 8 9 10 11 12 13
14 15 16 17 18 19 20
21 22 23 24 25 26 27
28 29 30
글 보관함