Given a Binary Tree, find the maximum sum path from a leaf to root. For example, in the following tree, there are three leaf to root paths 8->-2->10, -4->-2->10 and 7->10. The sums of these three paths are 16, 4 and 17 respectively. The maximum of them is 17 and the path for maximum is 7->10.
- Construct Special Binary Tree from given Inorder traversal
- Vertical Sum in a given Binary Tree | Set 1
- Find the maximum path sum between two leaves of a binary tree
- Maximum Path Sum in a Binary Tree
- Check whether a given Binary Tree is Complete or not | Set 1 (Iterative Solution)
- HashSet vs TreeSet in Java
- Preorder from Inorder and Postorder traversals
- Count pairs in a binary tree whose sum is equal to a given value x
- Find the maximum node at a given level in a binary tree
- Print nodes in top view of Binary Tree | Set 2
10 / \ -2 7 / \ 8 -4
1) First find the leaf node that is on the maximum sum path. In the following code getTargetLeaf() does this by assigning the result to *target_leaf_ref.
2) Once we have the target leaf node, we can print the maximum sum path by traversing the tree. In the following code, printPath() does this.
The main function is maxSumPath() that uses above two functions to get the complete solution.
Following are the nodes on the maximum sum path 7 10 Sum of the nodes is 17
Time Complexity: Time complexity of the above solution is O(n) as it involves tree traversal two times.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.