LEETCODE: Sum Root to Leaf Numbers
2015-01-03 16:15
357 查看
Given a binary tree containing digits from
a number.
An example is the root-to-leaf path
Find the total sum of all root-to-leaf numbers.
For example,
The root-to-leaf path
The root-to-leaf path
Return the sum = 12 + 13 =
/**
* Definition for binary tree
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
int sum;
void depthSearch(TreeNode *root, int num) {
if(root->left == NULL && root->right == NULL) sum += num;
if(root->left) depthSearch(root->left, num * 10 + root->left->val);
if(root->right) depthSearch(root->right, num * 10 + root->right->val);
}
int sumNumbers(TreeNode *root) {
if(root == NULL) return 0;
depthSearch(root, root->val);
return sum;
}
};
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.
/**
* Definition for binary tree
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
int sum;
void depthSearch(TreeNode *root, int num) {
if(root->left == NULL && root->right == NULL) sum += num;
if(root->left) depthSearch(root->left, num * 10 + root->left->val);
if(root->right) depthSearch(root->right, num * 10 + root->right->val);
}
int sumNumbers(TreeNode *root) {
if(root == NULL) return 0;
depthSearch(root, root->val);
return sum;
}
};
相关文章推荐
- LeetCode-Sum Root to Leaf Numbers
- leetcode 86: Sum Root to Leaf Numbers
- [LEETCODE] Sum Root to Leaf Numbers
- [Leetcode 39] 129 Sum Root to Leaf Numbers
- [LeetCode]Sum Root to Leaf Numbers
- leetcode Sum Root to Leaf Numbers(所有路径之和)
- leetcode Sum Root to Leaf Numbers(所有路径之和)
- LeetCode-Sum Root to Leaf Numbers
- leetcode:Sum Root to Leaf Numbers
- leetcode 86: Sum Root to Leaf Numbers
- LeetCode : Sum Root to Leaf Numbers
- [LeetCode] Sum root to leaf numbers
- LeetCode: Sum Root to Leaf Numbers
- leetcode -- Sum Root to Leaf Numbers
- [leetcode] Sum Root to Leaf Numbers
- LeetCode 129: Sum Root to Leaf Numbers
- LeetCode - Sum Root to Leaf Numbers
- [leetcode刷题系列]Sum Root to Leaf Numbers
- [leetcode]Sum Root to Leaf Numbers
- leetcode之Sum Root to Leaf Numbers