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
C:::maxPath
G:::maxPath
1
2
3
Input: [10,8,2,3,5,2,1]Output: [10,2,1]Explanation: The maximum sum path from root to leaf is10->8->5 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
B:::maxPath
D:::maxPath
1
2
3
Input: [-10,20,30,-10,50,35,100]Output: [-10,-20,10]Explanation: The maximum sum path from leaf to root is30->100 which has a sum of 130.
To find the minimum path sum from the root to a leaf in a binary tree, a Depth-First Search (DFS) traversal can be used to explore all paths from the root to each leaf node. By keeping track of the current sum and updating it if a leaf node is reached with a new minimum sum, we can determine the desired path.
Here is the approach:
Tree Traversal: Use DFS to traverse the tree from the root to each leaf node.
Track Minimum Sum: At each node, add its value to the current sum. When a leaf node is reached, update the minimum sum if the current path sum is less than the known minimum 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 smaller.