Given a binary tree containing digits from 0-9
only, each root-to-leaf path could represent a number.
An example is the root-to-leaf path 1->2->3
which represents the number 123
.
Find the total sum of all root-to-leaf numbers.
For example,
1 / \ 2 3
The root-to-leaf path 1->2
represents the number 12
.
The root-to-leaf path 1->3
represents the number 13
.
Return the sum = 12 + 13 = 25
.
基本思路:
前序遍历。
使用一个全局变量记录和。
每到一个叶子节点时,将得到的数字,进行累加并存和全局变量中。
在leetcode上实际运行时间为4ms.
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
int sumNumbers(TreeNode* root) {
int sum = 0;
sumNumbers(root, 0, sum);
return sum;
}
void sumNumbers(TreeNode* root, int number, int &sum) {
if (!root) return;
number = number * 10 + root->val;
if (!root->left && !root->right)
sum += number;
sumNumbers(root->left, number, sum);
sumNumbers(root->right, number, sum);
}
};
改进版:
可以使用函数返回值,来替代上面的全局变量和(函数第三变量)。
当为页子节点时,返回得到整数。
当为中间节点时,返回其左右子数所生成的整数和。
class Solution {
public:
int sumNumbers(TreeNode* root) {
return sumNumbers(root, 0);
}
int sumNumbers(TreeNode *root, int number) {
if (!root) return 0;
number = number * 10 + root->val;
if (!root->left && !root->right)
return number;
return sumNumbers(root->left, number) + sumNumbers(root->right, number);
}
};