Sum Root to Leaf Numbers
/** * Definition for binary tree * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { public: int sum = 0; void dfs(TreeNode *root,int num){ if(!root) return ;//空数 if(!root->left&&!root->right){//到达叶子节点 sum+=num*10+root->val; return ; } dfs(root->left,num*10+root->val);//遍历左右子树 dfs(root->right,num*10+root->val); return ; } int sumNumbers(TreeNode *root) { dfs(root,0); return sum; } };