Output: 19 Explanation: There are 4 leaf nodes in the tree, resulting in 4 leaf-to-root paths: 2 -> 4 -> 2 -> 1, 5 -> 2 -> 1, 6 -> 8 -> 3 -> 1, and 7 -> 8 -> 3 -> 1. Among these, the path 7 -> 8 -> 3 -> 1 has the maximum sum. The sum of this path is 7 + 8 + 3 + 1 = 19.
Output: 12 Explanation: There are 2 leaf nodes in the tree, resulting in 2 leaf-to-root paths: 5 -> -2 -> 1 and 8 -> 3 -> 1. Among these, the path 8 -> 3 -> 1 has the maximum sum. The sum of this path is 8 + 3 + 1 = 12.
Checking Every Path - O(n * h) Time and O(n) Space
The idea is to check of all possible path from root to leaf recursively. So we check for every path that is from root to every leaf and take the sum which path has the maximum sum.
Follow the steps below to solve the problem:
Traverse the binary tree from root to every node and maintain a parent map which contains the parent of a node.
While traversing, if the current node don't has left or right child, then the node is a leaf node.
When we encounter a leaf node, call a separate function which calculates the sum from that leaf to root.
The function calculates the sum by using parent map by recursively calling the function with parent node until we reach root.
Maintain a variable which keeps and updates the maximum sum.
Output
19
Time Complexity: O(n * h) Where n is number of nodes in tree and h is height of tree. Auxiliary Space: O(n)
Keeping Track of Maximum Sum - O(n) Time and O(h) Space
The idea is to keep track of current sum and maximum sum while traversing the tree and update maximum sum if at leaf node current sum is greater them maximum sum.
Follow the steps below to solve the problem:
If the node is the root, return its data.
If the node is a leaf, Check where current sum is greater than maximum sum, then update maximum sum.
For non-leaf nodes, update current sum and make recursive call on both left and right child.
Output
19
Time Complexity: O(n) Where n is number of nodes in tree. Auxiliary Space: O(h), where h is height of tree.