29. Sum of nodes on the longest path
GFG solution to the Sum of Nodes on the Longest Path problem using DFS.
The problem can be found at the following link: 🔗 Question Link
🧩 Problem Description
Given a binary tree, find the sum of the nodes on the longest path from the root to any leaf.
If there are multiple root-to-leaf paths of the same maximum length, return the maximum sum among them.
📘 Examples
Example 1
Input: root = [4,2,5,7,1,2,3,null,null,6]Output: 13
Explanation:Longest path is 4 → 2 → 1 → 6, sum = 4+2+1+6 = 13Example 2
Input: root = [1,2,3,4,5,6,7]Example 3
🔒 Constraints
Number of nodes in the tree: $1 \le N \le 10^6$
Node values: $0 \le \text{data} \le 10^4$
✅ My Approach
DFS Returning (Length, Sum)
Idea:
For each subtree, compute a pair
(maxDepth, maxSum), wheremaxDepthis the maximum root-to-leaf depth, andmaxSumis the maximum sum along any path of that depth.
Recurrence:
If left depth > right depth: take
(left.depth+1, left.sum + node->data).If right depth > left depth: take
(right.depth+1, right.sum + node->data).If equal: take
(left.depth+1, max(left.sum, right.sum) + node->data).
Answer:
After processing the root, its
secondcomponent is the desired sum.
📝 Time and Auxiliary Space Complexity
Expected Time Complexity: O(N), as we visit each node exactly once.
Expected Auxiliary Space Complexity: O(H), where H = height of the tree (recursion stack).
🧑💻 Code (C++)
🧑💻 Code (Java)
🐍 Code (Python)
🧠 Contribution and Support
For discussions, questions, or doubts related to this solution, feel free to connect on LinkedIn: 📬 Any Questions?. Let’s make this learning journey more collaborative!
⭐ If you find this helpful, please give this repository a star! ⭐
📍Visitor Count
Last updated