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.
- Find if there is a pair in root to a leaf path with sum equals to root's data
- Root to leaf path with maximum distinct nodes
- Print the longest leaf to leaf path in a Binary tree
- Given a binary tree, print all root-to-leaf paths
- Given a binary tree, print out all of its root-to-leaf paths one per line.
- Root to leaf paths having equal lengths in a Binary Tree
- Find the maximum path sum between two leaves of a binary tree
- Print path from root to a given node in a binary tree
- Sort the path from root to a given node in a Binary Tree
- Check if there is a root to leaf path with given sequence
- Root to leaf path sum equal to a given number
- Root to leaf path sum equal to a given number in BST
- Sum of nodes on the longest path from root to leaf node
- Root to leaf path product equal to a given number
- Maximum Path Sum in a Binary Tree
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.
Improved By : Subhrajyoti Choudhury