← Home

129. Sum Root to Leaf Numbers

LeetCode article · C++ solution
Website made by wuisabel-gif · Original C++ code by keineahnung2345
two pointersC++Markdown
129

I like to read this solution as a small machine: keep the useful information, throw away the noise. For 129. Sum Root to Leaf Numbers, the solution in this repository is mainly a two pointers solution.

Guide

What?

The first job is to translate the English prompt into state, transition, and stopping conditions. Instead of trying to be clever immediately, read the code as a sequence of questions:

  • What state are we keeping?
  • How do we move from one state to the next?
  • When do we know the answer is already determined?

For this file, the main tools are: two pointers.

Guide

When?

This pattern shows up when the brute force version has too many repeated checks, too many possible branches, or too much bookkeeping to do by hand. The accepted code reduces that pressure by storing exactly the information that remains useful later.

The important function names to track are sumNumbers.

Guide

Why?

The code is doing bookkeeping so your brain does not have to keep the entire search space open at once.

  • The final return is not magic; it is the invariant after the loops or recursion have finished doing their accounting.

Guide

How?

Walk through the solution in this order:

  1. Initialize the memory or helper structure.
  2. Process candidates in the order the invariant expects.
  3. Update the answer only when the current state is valid.
  4. Return the value that represents the fully processed input.

The most important competitive-programming habit here is to trust the invariant. Once the invariant is right, the loops become much less scary.

Guide

Complexity

  • Time: O(n) to O(n log n), depending on the dominant loop or data structure operation
  • Space: O(n) in the usual case for auxiliary containers or recursion

Guide

C++ Solution

Your submission

The accepted solution

solution.cpp
01//Runtime: 8 ms, faster than 30.69% of C++ online submissions for Sum Root to Leaf Numbers.
02//Memory Usage: 12.4 MB, less than 85.67% of C++ online submissions for Sum Root to Leaf Numbers.
03/**
04 * Definition for a binary tree node.
05 * struct TreeNode {
06 *     int val;
07 *     TreeNode *left;
08 *     TreeNode *right;
09 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
10 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
11 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
12 * };
13 */
14class Solution {
15public:
16    int sumNumbers(TreeNode* root, int initVal = 0) {
17        if(root == nullptr) return 0;
18        if(root->left == nullptr && root->right == nullptr){
19            //leaf node
20            return initVal + root->val;
21        }
22        
23        //non-leaf node
24        //accumulate the score from left and right subtrees
25        int sum = 0;
26        sum += sumNumbers(root->left, (initVal+root->val)*10) + sumNumbers(root->right, (initVal+root->val)*10);
27        
28        return sum;
29    }
30};

Cost

Complexity

Time
O(n) to O(n log n), depending on the dominant loop or data structure operation
Dominated by the main traversal, recursion, or data-structure operations in the code.
Space
O(n) in the usual case for auxiliary containers or recursion
Auxiliary state plus the answer structure where the problem requires one.