[Leetcode][Tree][Sum Root to Leaf Numbers]
非常简单的一个题,和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 };
更少的参数,更短的代码!