1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
|
class Solution
{
public:
int sumNumbers(TreeNode* root)
{
int res = 0;
// 如果根节点非空,开始递归
if (root)
dfs(root, res, 0);
return res;
}
void dfs(TreeNode* root, int& res, int cur)
{
// 将当前节点的值加到当前路径的数字中
cur = cur * 10 + root->val;
// 如果当前节点是叶节点,将路径数字加到结果中
if (!root->left && !root->right)
res += cur;
// 继续递归遍历左子树
if (root->left)
dfs(root->left, res, cur);
// 继续递归遍历右子树
if (root->right)
dfs(root->right, res, cur);
}
};
|