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 all root to leaf path sum of a Binary Tree
- Find maximum GCD value from root to leaf in a Binary tree
- Print the longest path from root to leaf in a Binary tree
- Boundary Root to Leaf Path traversal of a Binary Tree
- Print the first shortest root to leaf path in a Binary Tree
- Maximize count of set bits in a root to leaf path in a binary tree
- Maximum value of Bitwise AND from root to leaf in a Binary tree
- Find if there is a pair in root to a leaf path with sum equals to root's data
- GCD from root to leaf path in an N-ary tree
- 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
- Count the number of paths from root to leaf of a Binary tree with given XOR value
- Count of root to leaf paths in a Binary Tree that form an AP
- 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
- Count of root to leaf paths whose permutation is palindrome in a Binary Tree
- Maximum XOR with given value in the path from root to given node in the tree
- Print path from root to a given node 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.