Sum of Nodes on the Longest path from root to leaf node

Pattern: Path sums

medium

Walk every root-to-leaf path carrying its length and sum. Keep the best by length first; when two paths are equally long, keep the larger sum.

No verified practice link yet. The guide below states the problem in full, so you can still solve it here.

The problem

Return the sum of the nodes on the longest root-to-leaf path; if several are equally long, the largest sum among them. The example gives 13. The catalogue has no practice link for this one. Trees in the examples are written in level order, with null for a missing child, as on LeetCode.

Think first

  • What two numbers describe a path?
  • Which matters first?
  • What breaks a tie?

Hints

    Brute force, and why it fails

    List all paths, then pick: O(n × h).

    The key insight

    Comparing (length, sum) pairs at each leaf finds the answer in one walk.

    Dry run

    [4, 2, 5, 7, 1, 2, 3, null, null, 6]. The longest paths have 4 nodes: only 4, 2, 1, 6.

    Step 1 of 2

    The plan

    walk(n, len, sum): if null: return
                       sum += n.val
                       if leaf: best = max(best, (len, sum))
                       walk(left, len + 1, sum); walk(right, len + 1, sum)
    

    Complexity

    Time
    O(n)
    Space
    O(h)

    One walk.

    Edge cases

    • Empty tree: 0.
    • Ties in length.
    • Negative values.
    I've built my logic, show the code

    Java

    class Solution {
        private int bestLen, bestSum;
    
        public int sumOfLongRootToLeafPath(TreeNode root) {
            bestLen = 0;
            bestSum = 0;
            walk(root, 1, 0);
            return bestSum;
        }
    
        private void walk(TreeNode n, int len, int sum) {
            if (n == null) return;
            sum += n.val;
            if (n.left == null && n.right == null) {
                if (len > bestLen || (len == bestLen && sum > bestSum)) {   // longer wins; on a tie, the bigger sum
                    bestLen = len;
                    bestSum = sum;
                }
                return;
            }
            walk(n.left, len + 1, sum);
            walk(n.right, len + 1, sum);
        }
    }

    C++

    class Solution {
    public:
        int bestLen, bestSum;
    
        int sumOfLongRootToLeafPath(TreeNode* root) {
            bestLen = 0;
            bestSum = 0;
            walk(root, 1, 0);
            return bestSum;
        }
    
        void walk(TreeNode* n, int len, int sum) {
            if (n == NULL) return;
            sum += n->val;
            if (n->left == NULL && n->right == NULL) {
                if (len > bestLen || (len == bestLen && sum > bestSum)) {   // longer wins; on a tie, the bigger sum
                    bestLen = len;
                    bestSum = sum;
                }
                return;
            }
            walk(n->left, len + 1, sum);
            walk(n->right, len + 1, sum);
        }
    };

    Python

    class Solution:
        def sumOfLongRootToLeafPath(self, root) -> int:
            best = (0, 0)                           # (length, sum); longer wins, then the bigger sum
    
            def walk(n, length, total):
                nonlocal best
                if n:
                    total += n.val
                    if not n.left and not n.right:
                        best = max(best, (length, total))
                    walk(n.left, length + 1, total)
                    walk(n.right, length + 1, total)
    
            walk(root, 1, 0)
            return best[1]

    Common mistakes

    • Taking the largest sum regardless of length.
    • Counting a node with one child as a leaf.

    Similar problems