Problem Description:
Given a binary tree T, find the maximum path sum.
The path may start and end at any node in the tree.
Input Format:
The first and the only argument contains a pointer to the root of T, A.
Output Format:
Return an integer representing the maximum sum path.
Constraints:
1 <= Number of Nodes <= 7e4
-1000 <= Value of Node in T <= 1000
Example :
Input 1:
1
/ \
2 3
Output 1:
6
Explanation 1:
The path with maximum sum is: 2 -> 1 -> 3
Input 2:
-10
/ \
-20 -30
Output 2:
-10
Explanation 2
The path with maximu
m sum is: -10
Approach:
For each node there can be four ways that the max path goes through the node:
1. Node only
2. Max path through Left Child + Node
3. Max path through Right Child + Node
4. Max path through Left Child + Node + Max path through Right Child
The idea is to keep track of four paths and pick up the max one in the end. An important thing to note is, the root of every subtree need to return maximum path sum such that at most one child of root is involved. This is needed for the parent function call. In below code, this sum is stored in ‘max_single’ and returned by the recursive function.
Below is the implementation of the above approach:
No comments:
Post a Comment
Please do not enter any spam link in the comment box