Given a binary tree, find the maximum path sum. The path may start and end at any node in the tree.
For example: 1 / \ 2 3
Return |
One needs to handle three cases:
In addition compare with the max path so far and update accordingly. You are the first reader who actually spend time in writing a quality answer, not just copy and pasting code. I've awarded 10 extra points to you for your effort. Thanks and welcome! @1337c0d3r why the path has to contain the current root? Is it ok that the max sum path only lies in the left or right subtree? @Pan Consider the maxsum returned from maxPathSumHelper(node->left, lsum, maxsum); It covers the case that the max sum path lies in only the left subtree. @Pan Yes, it is entirely possible that the max sum path lies in the left or right subtree of the root. What @hukkatout mentioned by current root could be a subtree's root. (Remember: A subtree is a tree itself!) @IronmanZ @1337c0d3r ♦♦ i see what's going on. Thank you guys very much. |
Java doesn't allow to modify passed-in parameters. For this problem, we need to keep track two things during recursions: the max subpath sum and the current max sum for a given node. One way is to let the helper method return an array of two items, as shown in @Andy's solution; Another way is to pass in the current max as an array of one item.
|
@ponyma, Welcome! Please consider improving your answer with explanation and thought process. This will help others to understand your solution. |
|
public class Solution {
|
.
|