Given a binary Tree find the maximum path sum. The path may start and end at any node in the tree
All Answers
total answers (1)
Severity: 8192
Message: str_replace(): Passing null to parameter #3 ($subject) of type array|string is deprecated
Filename: libraries/Filtered_db.php
Line Number: 23
total answers (1)
we will use the following concept.
For each node there can be four ways that the maximum sum path goes through the node:
we will initialize the resultant maximum sum variable res with INT_MIN, then we will use an ampersand operator for that variable and keep changing it with the following cases: we 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 the below code, this sum is stored in 'temp' and returned by the recursive function.
Standard Node:
We will use the above node for further operation.
Pseudo Code:
Time Complexity for above code is O(n).
C++ Implementation:
Output