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

[Leetcode][Tree][Sum Root to Leaf Numbers]

时间:2014-07-05 22:03:48      阅读:251      评论:0      收藏:0      [点我收藏+]

标签:style   blog   color   for   代码   算法   

非常简单的一个题,和path sum非常类似。

 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     void sum(TreeNode *root, int now, int &res) {
13         if (root == NULL) {
14             return;
15         }
16         now = now * 10 + root->val;
17         if (root->left == NULL && root->right == NULL) {
18             res += now;
19         }
20         sum(root->left, now, res);
21         sum(root->right, now, res);
22     }
23     int sumNumbers(TreeNode *root) {
24         int res = 0;
25         sum(root, 0, res);
26         return res;
27     }
28 };

但是看完题解之后,发现题解中的解法还是比我的算法更优秀!赶紧学习!

 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 sum(TreeNode *root, int now) {
13         if (root == NULL) {
14             return 0;
15         }
16         now = now * 10 + root->val;
17         if (root->left == NULL && root->right == NULL) {
18             return now;
19         }
20         return sum(root->left, now) + sum(root->right, now);
21     }
22     int sumNumbers(TreeNode *root) {
23         return sum(root, 0);
24     }
25 };

更少的参数,更短的代码!

 

[Leetcode][Tree][Sum Root to Leaf Numbers],布布扣,bubuko.com

[Leetcode][Tree][Sum Root to Leaf Numbers]

标签:style   blog   color   for   代码   算法   

原文地址:http://www.cnblogs.com/poemqiong/p/3826136.html

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