简繁EN

LeetCodeNo. 077

[LeetCode with Python] 124. Binary Tree Maximum Path Sum

Contents

Problem

Problem page: https://leetcode.com/problems/binary-tree-maximum-path-sum/
Topics: Tree, Depth-first Search
Difficulty: Hard
Similar problems: (M) Path Sum, (M) Sum Root to Leaf Numbers

Given a binary tree, find the maximum path sum.

For this problem, a path is defined as any sequence of nodes from some starting node to any node in the tree along the parent-child connections. The path does not need to go through the root.

For example:
Given the below binary tree,

       1
      / \
     2   3

Return 6.


Analysis

This is a pretty simple binary tree recursion problem, but it still took me a while. Most of that time went into figuring out what the problem meant. The path that gives the "maximum path sum" doesn't have to go through root, and it can start and end at the same node (so the whole path is just one node).
Remember to use a class member variable max to track the largest path sum seen during the search and return it at the end.
When I finish processing a subtree and go back up one level, it's easy to return the subtree's "maximum path sum" by mistake when I should return the larger of its left and right path sums. That's because a path entering the subtree from its parent can follow only one branch, left or right.
Finally, keep in mind that the problem doesn't say the node values are positive or natural numbers. Knowing what leetcode is usually like, I'd assume negative numbers can show up too.


Code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
class Solution:
def __init__(self):
self.max = None

def doMaxPathSum(self, root):
if None == root:
return 0
left_sum = self.doMaxPathSum(root.left)
right_sum = self.doMaxPathSum(root.right)
max_left_sum = max(left_sum, 0)
max_right_sum = max(right_sum, 0)
cur_max = max_left_sum + max_right_sum + root.val
if None == self.max or cur_max > self.max:
self.max = cur_max
return max(max_left_sum + root.val, max_right_sum + root.val)

# @param root, a tree node
# @return an integer
def maxPathSum(self, root):
self.max = None
self.doMaxPathSum(root)
return self.max

Article link: https://xnerv.wang/en/leetcode-binary-tree-maximum-path-sum/