一、问题描述
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
.
基于先序遍历的思想,递归的条件是把当前的sum加上当前节点的val再传入下一个节点,递归结束的条件是当前节点指针为NULL返回0,如果当前节点左右节点指针为NULL返回sum*10加当前节点的值。
三、代码
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
int sumNumbers(TreeNode* root) {
int sum = 0;
return preSum(root, sum);
}
int preSum(TreeNode* root, int sum) {
if (root == NULL) {
return 0;
}
if (root->left == NULL&&root->right == NULL) {
return sum*10+ root->val;
}
return preSum(root->left, sum*10+root->val)+preSum(root->right, sum*10+root->val);
}
};