Find the maximum sum leaf-to-root path in a Binary Tree. This means that among all the paths from leaves to the root, find the path which has the maximum sum.
graph TD
A[10]
A --> B[8]
A --> C[2]
B --> D[3]
B --> E[5]
C --> F[2]
C --> G[1]
classDef maxPath fill:#f9f,stroke:#333,stroke-width:2px;
A:::maxPath
B:::maxPath
E:::maxPath
1
2
3
Input: [10,8,2,3,5,2,1]Output: [5,8,10]Explanation: The maximum sum path from leaf to root is5->8->10 which has a sum of 23.
graph TD
A[-10]
A --> B[20]
A --> C[30]
B --> D[-10]
B --> E[50]
C --> F[35]
C --> G[100]
classDef maxPath fill:#f9f,stroke:#333,stroke-width:2px;
A:::maxPath
C:::maxPath
G:::maxPath
1
2
3
Input: [-10,20,30,-10,50,35,100]Output: [100,30,-10]Explanation: The maximum sum path from leaf to root is100->30->-10 which has a sum of 120.
To find the maximum sum leaf-to-root path in a binary tree, we need to explore all paths from leaves to the root. This involves traversing the tree and at each node, keeping track of the maximum sum path rooted at that node.
Here is the approach:
Tree Traversal: Use Depth First Search (DFS) to explore all possible paths from leaves to the root.
Track Maximum Sum: For each path, calculate the sum and update the maximum sum if the current path’s sum exceeds the previously recorded maximum sum.
Store Path: As we traverse, keep track of nodes in the current path and update the path if the current path’s sum is greater.