129. 求根到叶子节点数字之和

 1 /**
 2  * Definition for a binary tree node.
 3  * struct TreeNode {
 4  *     int val;
 5  *     TreeNode *left;
 6  *     TreeNode *right;
 7  *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 8  * };
 9  */
10 class Solution 
11 {
12 public:
13     int helper(TreeNode* root, int sum)
14     {
15         if(!root) return 0;
16         if(!root->left && !root->right) return 10*sum + root->val;
17         return helper(root->left, 10*sum + root->val) + helper(root->right, 10*sum + root->val);
18     }
19     int sumNumbers(TreeNode* root) 
20     {
21         return helper(root, 0);
22     }
23 };

 

posted @ 2020-04-01 23:01  Jinxiaobo0509  阅读(118)  评论(0)    收藏  举报