您的位置:首页 > 其它

LeetCode 129: Sum Root to Leaf Numbers

2013-08-22 14:45 337 查看
Difficulty: 2

Frequency: 4

Problem:

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
.

Solution:

class Solution {
public:
int sumNumbers(TreeNode *root) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
int answer = 0;
DFS(root, 0, answer);
return answer;
}
void DFS(TreeNode * root, int i_current, int & answer)
{
if (root==NULL)
return;
if (root->left==NULL&&root->right==NULL)
{
answer+=i_current*10+root->val;
return;
}
if (root->left!=NULL)
DFS(root->left, i_current*10+root->val, answer);

if (root->right!=NULL)
DFS(root->right, i_current*10+root->val, answer);
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: