1 /*
 2  * @lc app=leetcode.cn id=129 lang=cpp
 3  *
 4  * [129] 求根到叶子节点数字之和
 5  */
 6 
 7 // @lc code=start
 8 /**
 9  * Definition for a binary tree node.
10  * struct TreeNode {
11  *     int val;
12  *     TreeNode *left;
13  *     TreeNode *right;
14  *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
15  * };
16  */
17 class Solution {
18 public:
19 
20 //深度优先搜索
21 //递归求出左右子树的和,然后相加得到最终结果。
22 
23 // 递归过程中, sum的值是不断变化的, 所以要将sum 的值也纳入递归函数中
24     int sumNumbers(TreeNode* root) {
25         return helper(root,0);        
26     }
27     
28     int helper(TreeNode* root, int sum){
29         if(root==nullptr) return 0;
30         if(!root->left&&!root->right) return sum+root->val;
31         sum+=root->val;
32         return helper(root->left,10*sum)+helper(root->right,10*sum);
33     }
34 };
35 // @lc code=end