---
description: '# Medium'
---

# 129. Sum Root to Leaf Numbers

{% hint style="info" %}
BFS, two ways: `sum = sum*10 + root.val`

1. Queue + while loop
2. Recursive
{% endhint %}

{% hint style="danger" %}
x = queue.front(), 队结构先进先出，queue.pop() 弹出第一个元素，这两是一对。
{% endhint %}

### Solution 1:  update evey node's value with path sum from root to this node

{% tabs %}
{% tab title="C++" %}
```cpp
/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
public:
    int sumNumbers(TreeNode* root) {
        queue<TreeNode*> q;
        // edge case
        if(root == NULL) return 0;
        if(root->left == NULL and root->right == NULL) return root->val;
        
        // regular case, BFS
        q.push(root);
        int sum = 0;
        while(!q.empty()) {
            int l = q.size();
            for(int i = 0; i < l; i ++) {
                root = q.front();
                q.pop();
                
                if(root->left != NULL) {
                    root->left->val = root->val*10 + root->left->val;
                    q.push(root->left);
                }
                if(root->right != NULL) {
                    root->right->val = root->val*10 + root->right->val;
                    q.push(root->right);
                }
                if(root->right == NULL and root->left == NULL) {
                    sum = sum + root->val;
                }
            }
        }
        
        return sum;
    }
};
```
{% endtab %}

{% tab title="Second Tab" %}

{% endtab %}
{% endtabs %}

### Solution 2: `subTree(root, sum)` means sum path from root to all leaves, including root.

{% tabs %}
{% tab title="C++" %}
```cpp
/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
public:
    int sumNumbers(TreeNode* root) {
        return subTree(root, 0);
    }
    
    int subTree(TreeNode* root, int sum) {
        // edge case
        if(root == NULL) return 0;
        
        // regular case, BFS, recursive
        sum = sum*10 + root->val;
        if(root->left == NULL and root->right == NULL) {
            return sum;
        }
        return subTree(root->left, sum)+subTree(root->right, sum);        
    }
};
```
{% endtab %}

{% tab title="Second Tab" %}

{% endtab %}
{% endtabs %}
