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
- Find all root to leaf path sum of a Binary Tree
- Print the longest leaf to leaf path in a Binary tree
- Boundary Root to Leaf Path traversal of a Binary Tree
- Maximize count of set bits in a root to leaf path in a binary tree
- Print the first shortest root to leaf path in a Binary Tree
- Print the longest path from root to leaf in a Binary tree
- Find maximum GCD value from root to leaf in a Binary tree
- GCD from root to leaf path in an N-ary tree
- Maximum value of Bitwise AND from root to leaf in a Binary tree
- Root to leaf path with maximum distinct nodes
- Remove nodes from Binary Tree such that sum of all remaining root-to-leaf paths is atleast K
- Shortest root to leaf path sum equal to a given number
- Sum of nodes on the longest path from root to leaf node
- Root to leaf path sum equal to a given number
- Given a binary tree, print out all of its root-to-leaf paths one per line.
- Given a binary tree, print all root-to-leaf paths
- Count of root to leaf paths in a Binary Tree that form an AP
- Count the number of paths from root to leaf of a Binary tree with given XOR value
- Count root to leaf paths having exactly K distinct nodes 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.
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.