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
each root-to-leaf path could represent a number.
An example is the root-to-leaf path
represents the number
Find the total sum of all root-to-leaf numbers.
For example,
The root-to-leaf path
the number
The root-to-leaf path
the number
Return the sum = 12 + 13 =
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);
}
};
Frequency: 4
Problem:
Given a binary tree containing digits from
0-9only,
each root-to-leaf path could represent a number.
An example is the root-to-leaf path
1->2->3which
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->2represents
the number
12.
The root-to-leaf path
1->3represents
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);
}
};
相关文章推荐
- LeetCode 129 Sum Root to Leaf Numbers
- leetcode[129] Sum Root to Leaf Numbers
- LeetCode: Sum Root to Leaf Numbers [129]
- leetcode——129——Sum Root to Leaf Numbers
- LeetCode - 129 - Sum Root to Leaf Numbers
- LeetCode 129 Sum Root to Leaf Numbers
- leetcode_129_Sum Root to Leaf Numbers
- leetcode129 Sum Root to Leaf Numbers java 算法
- LeetCode 129: Sum Root to Leaf Numbers
- leetcode || 129、Sum Root to Leaf Numbers
- [LeetCode129]Sum Root to Leaf Numbers
- leetcode 129 Sum Root to Leaf Numbers
- LeetCode(129) Sum Root to Leaf Numbers
- LeetCode129—Sum Root to Leaf Numbers
- LeetCode 129: Sum Root to Leaf Numbers 树的遍历
- LeetCode129:Sum Root to Leaf Numbers
- LeetCode(129) Sum Root to Leaf Numbers
- 【LEETCODE】129-Sum Root to Leaf Numbers [Python]
- leetcode_c++:树:Sum Root to Leaf Numbers(129)
- [leetcode 129] Sum Root to Leaf Numbers