Thursday, August 20, 2015

Leetcode 124. Binary Tree Maximum Path Sum

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

Because the path is from node to node, the nodes of this path will form a tree (for only one node, we see it as a tree here). Note even the start node is negative, the solution is still correct: the real path will replace the maxSum afterwards.

Solution:
# T:O(n) S:O(h)
class Solution:
    maxSum = float("-inf")
    # @param root, a tree node
    # @return an integer
    def maxPathSum(self, root):
        self.maxPathSumRecu(root)
        return self.maxSum
    
    def maxPathSumRecu(self, root):
        if root is None:
            return 0
        left = max(0, self.maxPathSumRecu(root.left))
        right = max(0, self.maxPathSumRecu(root.right))
        self.maxSum = max(self.maxSum, root.val + left + right)
        return root.val + max(left, right)
Run Time: 164 ms

No comments:

Post a Comment