Leetcode在线编程 sum-root-to-leaf-numbers
题目链接
题目描述
Given a binary tree containing digits from0-9only, each root-to-leaf path could represent a number.
An example is the root-to-leaf path1->2->3which represents the number123.
Find the total sum of all root-to-leaf numbers.
For example,
1
/ \
2 3
The root-to-leaf path1->2represents the number12.
The root-to-leaf path1->3represents the number13.
Return the sum = 12 + 13 =25.
题意
以根到每一个叶结点的遍历序列当成一个数,求这些数之和
解题思路
逐层递归,考虑利用第二个函数,单用一个函数实现起来比较麻烦
在另一个函数里设置一个参数cnt代表当前的遍历序列,因为题目要
求返回的是int,所以这里用int来保存遍历序列,不会产生越界问题
cnt要怎么去更新呢
我们可以考虑每次cnt*10再加上当前节点的值就可以了
当根节点为时cnt为0,root->val设置为rv
即root->val + cnt *10
因为前面的序列乘以10再加上该节点的val的话,就是新的遍历序列
以此类推
AC代码
class Solution {
public:
int dfs(TreeNode *root ,int cnt)
{
if(root==NULL)
return 0;
if(root->left==NULL && root->right ==NULL)
return root->val + cnt * 10;
return dfs(root->left ,root->val + cnt * 10) + dfs(root->right,root->val + cnt * 10);
}
int sumNumbers(TreeNode *root) {
return dfs(root,0);
}
};