/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { public: int sumNumbers(TreeNode* root) { return sum(root,0); } int sum(TreeNode *root,int num){ if(root==NULL) return 0; if(root->left ==NULL && root->right == NULL) return num*10+root->val; return sum(root->left,num*10+root->val)+sum(root->right,num*10+root->val); } };
递归的思想