首页 > 代码库 > sum-root-to-leaf-numbers——dfs

sum-root-to-leaf-numbers——dfs

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

An example is the root-to-leaf path1->2->3which represents the number123.

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

For example,

    1
   /   2   3

 

The root-to-leaf path1->2represents the number12.
The root-to-leaf path1->3represents the number13.

Return the sum = 12 + 13 =25.

 1 /**
 2  * Definition for binary tree
 3  * struct TreeNode {
 4  *     int val;
 5  *     TreeNode *left;
 6  *     TreeNode *right;
 7  *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 8  * };
 9  */
10 class Solution {
11 public:
12     int sumNumbers(TreeNode *root) {
13         if(root==NULL)
14             return 0;
15         res=0;
16         dfs(root,0);
17         return res;
18     }
19     void dfs(TreeNode *root,int num){
20         if(root!=NULL){
21             num=num*10+root->val;
22         }
23         if(root->left==NULL&&root->right==NULL){
24             res+=num;
25         }
26         if(root->left!=NULL){
27             dfs(root->left,num);
28         }
29         if(root->right!=NULL){
30             dfs(root->right,num);
31         }
32     }
33     int res;
34 };

 

sum-root-to-leaf-numbers——dfs