leetCode(36):Sum Root to Leaf Numbers 分类: leetCode 2015-07-13 16:00 157人阅读 评论(0) 收藏
2015-07-13 16:00
423 查看
Given a binary tree containing digits from
could represent 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 =
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 a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { public: void sumNumber(TreeNode* root, int sum,int& result) { if (root == NULL) return;//直接返回 sum = sum * 10 + root->val; if (root->left == NULL && root->right == NULL) {//相加求和返回 result += sum; return; } sumNumber(root->left, sum,result); sumNumber(root->right, sum,result); } int sumNumbers(TreeNode* root) { int result = 0; sumNumber(root, 0, result); return result; } };
相关文章推荐
- Android 获取和设置屏幕亮度的模式和值
- Image$$VECTOR$$Base
- How-to: effective store kafka data into hdfs via spark streaming
- 如何把默认壁纸改为动态壁纸
- jQuery中DOM和CSS操作
- iOS真机沙盒文件查看 图片批量存储/获取/删除
- 小玩Android布局中的weight(权重)
- Oracle 语句递归查找父子关系语句
- 【日常学习】【背包DP】codevs1115 开心的金明题解
- Redis 数据序列化方法 serialize, msgpack, json, hprose 比较
- GRE写作必备句型
- php随机显示指定文件夹下图片的方法
- fd_set 用法 socket
- jquery提升性能最佳实践小结
- hadoop 格式化后没有datanode节点
- do{}while(0)
- UVA 10820 Send a Table euler_phi功能
- Convert Sorted Array to Binary Search Tree
- INFA调优
- HDU -- 3468 Treasure Hunting (最大流+BFS)