binary-tree-maximum-path-sum
Problem
Problem Description
Given a non-empty 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 must contain at least one node and does not need to go through the root.
Example 1:
Input: [1,2,3]
1
/ \
2 3
Output: 6 (1+2+3)
Example 2:
Input: [-10,9,20,null,null,15,7]
-10
/ \
9 20
/ \
15 7
Output: 42(15+20+7)Solution
For this problem, we can define a global parameter max and init max = Integer.MIN_VALUE; personally do not like it, in real industry project, not recommend this way though. Personally perfer to define a class (object) to hold max value. below will post both code.
As problem described, maximum path sum go be left subtree, right subtree, or include left subtree + right subtree + root.val.
Recursively iterate subtree,
iterate left subtree,
if left < 0, discard left value, keep 0.iterate right subtree,
if right < 0, discard right value, keep 0.compute maximum value (3 possible calculations)
max = max(max, left + right + node.val)return max(left, right) + node.val;
Code
Code with global parameter
Code with class to hold object
Last updated
Was this helpful?