链接: https://oj.leetcode.com/problems/sum-root-to-leaf-numbers/
dfs..sum保存中间结果.每计算完一条路径,就更新ans
/** * 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 ans; int sumNumbers(TreeNode *root) { ans=0; if(root==NULL) return 0; dfs(root,root->val); return ans; } void dfs(TreeNode *root,int sum) { if(root->left==NULL&&root->right==NULL) { ans+=sum; return ; } if(root->left) dfs(root->left,sum*10+root->left->val); if(root->right) dfs(root->right,sum*10+root->right->val); } };