Leetcode: Sum Root to Leaf Numbers
题目
https://oj.leetcode.com/problems/sum-root-to-leaf-numbers/
分析
DFS
代码
class Solution
{
public:
int sumNumbers(TreeNode *root)
{
int solution = 0;
if (!root)
return 0;
dfs(root, solution);
return sum;
}
void dfs(TreeNode *root, int solution)
{
if (!root->left && !root->right)
{
solution = solution * 10 + root->val;
sum += solution;
}
else
{
solution = solution * 10 + root->val;
if (root->left)
dfs(root->left, solution);
if (root->right)
dfs(root->right, solution);
}
}
private:
int sum = 0;
};
本文章迁移自http://blog.csdn.net/timberwolf_2012/article/details/38928263