githubEdit

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 Linkarrow-up-right

🧩 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]

Binary tree example for longest path sum

Output: 13
Explanation:

Binary tree example for longest path sum

Longest path is 4 → 2 → 1 → 6, sum = 4+2+1+6 = 13

Example 2

Input: root = [1,2,3,4,5,6,7]

Binary tree example for longest path sum

Binary tree example for longest path sum

Example 3

Binary tree example for longest path sum

Binary tree example for longest path sum

🔒 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)

  1. Idea:

    • For each subtree, compute a pair (maxDepth, maxSum), where maxDepth is the maximum root-to-leaf depth, and maxSum is the maximum sum along any path of that depth.

  2. 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).

  3. Answer:

    • After processing the root, its second component 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++)

chevron-right⚡ View Alternative Approaches with Code and Analysishashtag

📊 2️⃣ Recursive with global state

💡 Algorithm Steps:

  1. Maintain two global variables:

    • maxLen = maximum depth seen so far

    • maxSum = maximum sum for paths of length maxLen

  2. Define helper void dfs(Node* node, int curLen, int curSum):

    • If node == nullptr:

      • If curLen > maxLen, update maxLen = curLen, maxSum = curSum.

      • Else if curLen == maxLen, maxSum = max(maxSum, curSum).

      • Return.

    • Recurse on node->left with (curLen+1, curSum + node->data).

    • Recurse on node->right with (curLen+1, curSum + node->data).

  3. Call dfs(root, 0, 0) and return maxSum.

📝 Complexity Analysis:

  • Time: 🟢 O(N)

  • Auxiliary Space: 🔸 O(H) (recursion depth)

Why This Approach?

  • Simple to implement and reason about.

  • Directly tracks global best without packing/unpacking pairs.

🆚 Comparison of Approaches

Approach

⏱️ Time

🗂️ Auxiliary Space

Pros

⚠️ Cons

🔁 DFS Returning Pair

🟢 O(N)

🟢 O(H)

Pure functional, no globals

Slightly more code to return and unpack pair

▶️ Recursive with Global State

🟢 O(N)

🔸 O(H)

Very straightforward, minimal return values

Uses mutable global variables

Best Choice?

Scenario

Recommended Approach

🏆 Clean, side-effect-free logic

🥇 DFS Returning Pair

⚡️ Quick implementation & readability

🥈 Recursive with Globals

🧑‍💻 Code (Java)

🐍 Code (Python)

🧠 Contribution and Support

For discussions, questions, or doubts related to this solution, feel free to connect on LinkedIn: 📬 Any Questions?arrow-up-right. Let’s make this learning journey more collaborative!

If you find this helpful, please give this repository a star!


📍Visitor Count

Last updated