题目:
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
.
思路:DFS,记录当前路径所代表的数,到达叶子结点后计算和。
class Solution {
public:
int trace;
void dfs(TreeNode* root, int& sum) {
trace = trace * 10 + root->val;
if (root->left == nullptr && root->right == nullptr) { //reach the leaf
sum += trace;
trace = (trace - root->val) / 10;
return;
}
if (root->left != nullptr) dfs(root->left, sum);
if (root->right != nullptr) dfs(root->right, sum);
trace = (trace - root->val) / 10;
}
int sumNumbers(TreeNode *root) {
if (root == nullptr) return 0;
int sum = 0;
trace = 0;
dfs(root, sum);
return sum;
}
};
总结:类似题型可以将trace定义为static,定义在递归函数中。(Leetcode并不鼓励这样做,因为当同时测试多个输入集合时,trace并不会每次都清0. 对于本题而言,trace返回到根节点后必然为0,但是其他题可能会报错。因此所有的trace全部定义为全局变量,但单从函数的角度考虑,定义为static显然更好。)复杂度O(2^n),n为层数。或O(n),n为node数。