[129]Sum Root to Leaf Numbers
2015-12-08 21:54
399 查看
【题目描述】
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 =
【思路】
用递归实现深搜就可以了,一次AC。
【代码】
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.
【思路】
用递归实现深搜就可以了,一次AC。
【代码】
/** * 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: vector<int> ans; void dfs(TreeNode* root,int sum){ if(root->left==NULL&&root->right==NULL) ans.push_back(sum*10+root->val); if(root->left!=NULL) dfs(root->left,sum*10+root->val); if(root->right!=NULL) dfs(root->right,sum*10+root->val); } int sumNumbers(TreeNode* root) { int ret=0; if(root==NULL) return 0; dfs(root,0); for(int i=0;i<ans.size();i++){ ret+=ans[i]; } return ret; } };
相关文章推荐
- 011 MATLAB进阶笔记:告别for循环,走向新巅峰
- 第一次使用redis看的文章(转)
- 开发datastage parallel routine
- java(7)--UDP传输
- 新建类时出现警告的几种情况
- 绘制像素到屏幕
- Qt信号槽机制的实现(面试的感悟,猜测每一个类保存的一个信号和槽的二维表,实际使用函数指针 元对象 还有类型安全的检查设定等等)
- http收藏的文章
- 虚拟机的几种上网方式
- 旧Mj下拉刷新 An instance 0xca90200 of class UITableView was deallocated while key value observers were s
- PHP FastCGI进程管理器PHP-FPM的架构
- mysql瓶颈等
- 开博
- Unity leapmotion开发实录(3)
- 信息安全系统设计基础实验五报告
- PMCAFF产品经理第一课 | 杭州站 现场集锦
- IAR + STM32固件库 启动文件startup_stm32f10x_hd.s功用及注释
- 12-5和12-6考试总结
- can总线保护电路
- 使用spring的JdbcTemplate查询