码迷,mamicode.com
首页 > 其他好文 > 详细

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

时间:2017-06-13 00:03:01      阅读:185      评论:0      收藏:0      [点我收藏+]

标签:example   struct   ret   span   null   which   contain   git   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

标签:example   struct   ret   span   null   which   contain   git   dfs   

原文地址:http://www.cnblogs.com/zl1991/p/6995398.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!