iT邦幫忙

2022 iThome 鐵人賽

0
自我挑戰組

LeetCode Top 100 Liked系列 第 54

[Day 54 - 1] Binary Tree Maximum Path Sum (Hard)

  • 分享至 

  • xImage
  •  

124. Binary Tree Maximum Path Sum

Solution 1: DFS + Recursive

# 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.maxPathSumInHistory = -2147483648
        
    def dfs(self, root):
        if not root:
            return 0
        
        lftMaxPathSum = max(self.dfs(root.left), 0)
        rhtMaxPathSum = max(self.dfs(root.right), 0)
        curPathSum = root.val + lftMaxPathSum + rhtMaxPathSum
        
        self.maxPathSumInHistory = max(self.maxPathSumInHistory, curPathSum)
        return root.val + max(lftMaxPathSum, rhtMaxPathSum)
        
    def maxPathSum(self, root: Optional[TreeNode]) -> int:
        self.dfs(root)
        return self.maxPathSumInHistory

Time Complexity: O(N)
Space Complexity: O(N) // Call stack of recursion

Solution 2: DFS + Iterative

Time Complexity: O(N)
Space Complexity: O(N)

Reference

https://leetcode.com/problems/binary-tree-maximum-path-sum/discuss/603423/Python-Recursion-stack-thinking-process-diagram


上一篇
[Day 53] Validate Binary Search Tree (Medium)
下一篇
[Day 54 - 2] Construct Binary Tree from Preorder and Inorder Traversal (Medium)
系列文
LeetCode Top 100 Liked77
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言