124. Binary Tree Maximum Path Sum
class Solution:
def maxPathSum(self, root: TreeNode) -> int:
max_path = float("-inf") # placeholder to be updated
def get_max_gain(node):
nonlocal max_path # This tells that max_path is not a local variable
if node is None:
return 0
gain_on_left = max(get_max_gain(node.left), 0) # Read the part important observations
gain_on_right = max(get_max_gain(node.right), 0) # Read the part important observations
current_max_path = node.val + gain_on_left + gain_on_right # Read first three images of going down the recursion stack
max_path = max(max_path, current_max_path) # Read first three images of going down the recursion stack
return node.val + max(gain_on_left, gain_on_right) # Read the last image of going down the recursion stack
get_max_gain(root) # Starts the recursion chain
return max_path
Runtime: 84 ms, faster than 81.53% of Python3 online submissions for Binary Tree Maximum Path Sum.
Memory Usage: 21.4 MB, less than 70.28% of Python3 online submissions for Binary Tree Maximum Path Sum.
Author And Source
이 문제에 관하여(124. Binary Tree Maximum Path Sum), 우리는 이곳에서 더 많은 자료를 발견하고 링크를 클릭하여 보았다 https://velog.io/@jwade/124.-Binary-Tree-Maximum-Path-Sum저자 귀속: 원작자 정보가 원작자 URL에 포함되어 있으며 저작권은 원작자 소유입니다.
우수한 개발자 콘텐츠 발견에 전념 (Collection and Share based on the CC Protocol.)