Sum-root-to-leaf-Numbers
2018-03-23 14:54
260 查看
题目描述
Given a binary tree containing digits from0-9only, each root-to-leaf path could represent a number.An example is the root-to-leaf path1->2->3which represents the number123.Find the total sum of all root-to-leaf numbers.For example, 1/ \
2 3
The root-to-leaf path1->2represents the number12.
The root-to-leaf path1->3represents the number13.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 sumNumbers(TreeNode *root) { if(root==NULL) return 0; return sumRec(root, 0); } int sumRec(TreeNode *root, int presum) { int x = presum*10 + root->val; if(root->left==NULL && root->right==NULL) //左右子树都没有; { return x; } if(root->left==NULL) //没有左子树; { return sumRec(root->right, x); } if(root->right==NULL) //没有右子树 { return sumRec(root->left, x); } return sumRec(root->left, x) + sumRec(root->right, x); //都要左右子树; } };
相关文章推荐
- leetcode[129] Sum Root to Leaf Numbers
- sum-root-to-leaf-numbers
- sum-root-to-leaf-numbers Java code
- 129 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 理解分析
- Sum Root to Leaf Numbers
- Sum Root to Leaf Numbers
- leetcode——129——Sum Root to Leaf Numbers
- LeetCode - Sum Root to Leaf Numbers
- [LeetCode] - Sum Root to Leaf Numbers
- 129.leetcode Sum Root to Leaf Numbers(medium)[深度遍历DFS]
- Sum Root to Leaf Numbers
- 129. Sum Root to Leaf Numbers
- 树——sum-root-to-leaf-numbers
- LeetCode 129 Sum Root to Leaf Numbers(递归求和)
- DFS Sum Root to Leaf Numbers
- LeetCode129 Sum Root to Leaf Numbers