题目

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,



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.

分析

按照二叉树的深度遍历,累计所有路径组成整数的和。

使用二叉树的递归深度优先遍历实现!

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:
int sumNumbers(TreeNode* root) {
int ret = 0;
if (!root)
return ret;
else if (!root->left && !root->right)
{
ret = root->val;
return ret;
}
else
dfs(root, root->val , ret); return ret;
} //深度优先遍历,得到所有根节点到叶子节点的路径和
void dfs(TreeNode *root, int val, int &sum)
{
if (!root->left && !root->right)
sum += val;
if (root->left)
{
dfs(root->left, val * 10 + root->left->val, sum);
} if (root->right)
{
dfs(root->right, val * 10 + root->right->val, sum);
}
}
};

GitHub测试程序源码

最新文章

  1. IOS ScrollView放大缩小点击位置并居中
  2. Xamarin 手动安装步骤+破解(最新版Xamarin V3)
  3. SharePoint:WebPartPageUserException This page has encountered a critical error
  4. :radio :checkbox
  5. 《极客学院 --NSAttributedString 使用详解-4-UITextKit 简介》学习笔记(待处理)
  6. Android开发探秘之一:创建可以点击的Button
  7. Java 中判断两个对象是否相等
  8. 【转】对Android开发者有益的40条优化建议
  9. OpenGL超级宝典第5版&&开发环境搭建
  10. QT多线程笔记
  11. IDisposable 接口2
  12. Codeforces 286E
  13. 如何滚动更新 Service?- 每天5分钟玩转 Docker 容器技术(102)
  14. [UE4]Circular Throbber,圆形的、环形的动态图标
  15. 区块链 + 大数据:EOS存储
  16. 【转】理解*(void**)
  17. echarts实现环形图
  18. ERP客户关系渠管理添加和修改联系人(二十一)
  19. XML序列化、反序列化
  20. Golang之定时器,recover

热门文章

  1. NET Core 2.0 使用支付宝
  2. RabbitMQ使用教程(一)RabbitMQ环境安装配置及Hello World示例
  3. 《springcloud 一》搭建注册中心,服务提供者,服务消费者
  4. 关于下载文件封装的两个类(Mars)
  5. Linux下常用的数据恢复工具
  6. MVC4学习之官方教程中迁移版本库报错
  7. Microsoft Exchange本地和Exchange Online可以与第三方服务共享
  8. 【UML】活动图Activity diagram(转)
  9. UVA 536 TreeRocvery 树重建 (递归)
  10. 七、vue中将token存到cookie