leetcode Sum Root to Leaf Numbers
2015-12-09 20:12
477 查看
原题链接:https://leetcode.com/problems/sum-root-to-leaf-numbers/
An example is the root-to-leaf path 1->2->3 which 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->2 represents the number 12.
The root-to-leaf path 1->3 represents the number 13.
Return the sum = 12 + 13 = 25.
Description
Given a binary tree containing digits from 0-9 only, each root-to-leaf path could represent a number.An example is the root-to-leaf path 1->2->3 which 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->2 represents the number 12.
The root-to-leaf path 1->3 represents 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: int ans; int sumNumbers(TreeNode* root) { if (!root) return 0; ans = 0; dfs(root, 0); return ans; } void dfs(TreeNode *x, int v) { if (!x) return; if (!x->left && !x->right) { ans += x->val + v * 10; } dfs(x->left, v * 10 + x->val); dfs(x->right, v * 10 + x->val); } };
相关文章推荐
- python-变量命名规范
- oVirt试验迁移虚拟机总结小记
- MSSQL 问题集锦
- 黑马程序员——OC之NSString
- 浩辰电气表格和天正电气表格
- appium在MAC上环境搭建
- 记录我开始学习 Git的路程
- iOS symbolicatecrash工具crash日志分析
- XMPP系列 - 02 - 服务器/客户端
- 旅行
- 单例设计模式
- springmvc-入门
- Codeforces Round #334 (Div. 2)
- leetcode Clone Graph
- linux 安装 7-Zip
- Genymotion
- python爬取网易评论
- Spring-hibernate-事务处理详解及案例<六>
- 前端开发小结
- 阅读《驯服烂代码》