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

LeetCode 129. Sum Root to Leaf Numbers

时间:2016-03-02 22:00:50      阅读:123      评论:0      收藏:0      [点我收藏+]

标签:

 1 /**
 2  * Definition for a binary tree node.
 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 sum;
13     
14     void process(TreeNode* root, int& sum, int cur){
15         
16         cur = cur * 10 + root->val;
17         if(!root->left && !root->right){
18             sum += cur;
19             return;
20         }
21         if(root->left) process(root->left, sum, cur);
22         if(root->right) process(root->right, sum, cur);
23         
24     }
25     
26     int sumNumbers(TreeNode* root) {
27         if(!root) return 0;
28         
29         sum = 0;
30         process(root, sum, 0);
31         return sum;
32     }
33 };

 

LeetCode 129. Sum Root to Leaf Numbers

标签:

原文地址:http://www.cnblogs.com/co0oder/p/5236478.html

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