Problem description: http://oj.leetcode.com/problems/sum-root-to-leaf-numbers/
Basic idea: To store the num vector in every node of tree by starting from leaf, the go up util to root.
1 class Solution { 2 public: 3 vector<vector<int>> subNumbers(TreeNode *root) { 4 vector<vector<int>> sums; 5 if(root == NULL) 6 return sums; 7 8 if(root->left == NULL && root->right == NULL){ 9 vector<int> seq; 10 seq.push_back(root->val); 11 sums.push_back(seq); 12 return sums; 13 } 14 15 vector<vector<int>> left_sums = subNumbers(root -> left); 16 for(auto item: left_sums) { 17 item.insert(item.begin(), root->val); 18 sums.push_back(item); 19 } 20 21 vector<vector<int>> right_sums = subNumbers(root -> right); 22 for(auto item: right_sums) { 23 item.insert(item.begin(), root->val); 24 sums.push_back(item); 25 } 26 return sums; 27 } 28 29 int pow10(int n) { 30 int ret = 1; 31 for(int i = 0; i < n; i++) 32 ret = ret * 10; 33 34 return ret; 35 } 36 37 int sumNumbers(TreeNode *root) { 38 // Note: The Solution object is instantiated only once and is reused by each test case. 39 int sum = 0; 40 vector<vector<int>> sums = subNumbers(root); 41 for(auto v : sums){ 42 int tmp_sum = 0; 43 for(int i = v.size() - 1; i >= 0; i -- ) { 44 tmp_sum += v[i] * pow10(v.size() - 1 - i); 45 } 46 sum += tmp_sum; 47 } 48 return sum; 49 } 50 };