Description:
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.
Note:
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
.
Solution:
Analysis and Thinking:
题目要求求出输入二叉树的所有路径代表的数字的相加值,其中每一条路径都是根节点到叶节点的,且按顺序组合起来代表一个数字,每一个节点的数字为0-9。可利用递归法实现,因为输出是树的从根到叶的节点的所有路径相加结果,因此,递归条件可设为当前记录的Sum值x10后加上当前遍历的节点的值,然后再把更新的sum传给下一个递归过程。结束条件可设为,若遍历的当前节点为叶子,将目前sum值x10加上叶子值,加到最终结果记录变量当中,最终我们需要把左右子树的和相加。
Steps:
1.判断当前节点是否为空,若是,返回0
2.判断当前节点是否为叶节点,若是,将递归累加和结果x10后加上叶子值,返回
3.如果当前遍历节点为非叶子节点,则遍历其左右子树,并把其左右子树相加,当做最终和值
Codes:
class Solution
{
public:
int sumNumbers(TreeNode *root)
{
return sumNumbers_2(root,0)
}
int sumNumbers_2(TreeNode* root,int record)
{
if(root==NULL) return 0;//特殊情况,若当前节点为空,返回0
if(root->right==NULL&&root->left==NULL) //特殊情况,如果当前值为叶子节点
{
return record*10+root->value;
}
return sumNumbers_2(root->left,record*10+root->value)+sumNumbers_2(root->right,record*10+root->value) //非叶子节点,将左右子树结果相加
}
};
Results: