Sum Root to Leaf Numbers

Given a binary tree containing digits from 0-9 only, each root-to-leaf path could represent a number.

An example is the root-to-leaf path 1->2->3 which represents the number 123.

Find the total sum of all root-to-leaf numbers.

For example,

    1
   / 
  2   3

The root-to-leaf path 1->2 represents the number 12.
The root-to-leaf path 1->3 represents the number 13.

Return the sum = 12 + 13 = 25

思路

递归。每一层如果有子节点的话,就把之前路径的值往下传递,直到到达叶节点加到最终结果里。

 1     int result,tmp;
 2     void calSum(TreeNode *root){
 3         if(root == NULL)
 4             return;
 5         if(root->left == NULL && root->right == NULL){
 6             tmp = tmp*10+(root->val);
 7             result += tmp;
 8             tmp /= 10;
 9             return;
10         }
11         if(root->left != NULL){
12             tmp = tmp*10+(root->val);
13             calSum(root->left);
14             tmp /= 10;
15         }
16         if(root->right != NULL){
17             tmp = tmp*10+(root->val);
18             calSum(root->right);
19             tmp /= 10;
20         }
21     }
22     int sumNumbers(TreeNode *root) {
23         // Note: The Solution object is instantiated only once and is reused by each test case.
24         result = 0;
25         tmp = 0;
26         calSum(root);
27         return result;
28     }

 第二次代码

 1     void search(TreeNode* root, int &result, int last){
 2         if(root){
 3             if(!root->left && !root->right)
 4                 result += (last*10+root->val);
 5             else{
 6                 last = last*10+root->val;
 7                 search(root->left, result, last);
 8                 search(root->right, result, last);
 9             }
10         }
11     }
12     int sumNumbers(TreeNode *root) {
13         int result = 0;
14         search(root, result, 0);
15         return result;
16     }
原文地址:https://www.cnblogs.com/waruzhi/p/3376613.html