该题可以用DFS解决,在DFS时记录path,当到达leaf时将path所表示的数加到sum上。
1 class Solution { 2 public: 3 int sumNumbers(TreeNode *root) { 4 vector<int> path; 5 int sum = 0; 6 dfs(root,path,sum); 7 return sum; 8 } 9 void dfs(TreeNode * root, vector<int> & path, int & sum){ 10 if(!root) return; 11 path.push_back(root->val); 12 if(!root->left && !root->right){ 13 int len = path.size(); 14 for(int i = 0; i < len; i++) 15 sum += path[i]*pow(10.0,len-i-1); 16 } 17 if(root->left) dfs(root->left,path,sum); 18 if(root->right) dfs(root->right,path,sum); 19 path.pop_back(); 20 } 21 };
Sum Root to Leaf Numbers,布布扣,bubuko.com
原文:http://www.cnblogs.com/Kai-Xing/p/3897690.html