题目 LeetCode 129 Root to Leaf Numbers
水题
/**
* 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 ans =0;
int sumNumbers(TreeNode* root) {
ans =0;
dfs(root,0);
return ans;
}
void dfs(TreeNode* root,int num)
{
if(root==NULL) return;
if(root->left!=NULL)
{
dfs(root->left,num*10+root->val);
}
if(root->right!=NULL)
{
dfs(root->right,num*10+root->val);
}
if(root->left==NULL&&root->right==NULL)
ans+=num*10+root->val;
}
};