sum-root-to-leaf-numbers——dfs
2024-08-28 15:24:05
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 ;
res=;
dfs(root,);
return res;
}
void dfs(TreeNode *root,int num){
if(root!=NULL){
num=num*+root->val;
}
if(root->left==NULL&&root->right==NULL){
res+=num;
}
if(root->left!=NULL){
dfs(root->left,num);
}
if(root->right!=NULL){
dfs(root->right,num);
}
}
int res;
};
最新文章
- [vs2008]Visual Studio 2008 SP1添加或删除功能提示查找SQLSysClrTypes.msi文件
- [LeetCode] Remove K Digits 去掉K位数字
- 改变bootstrap-wysiwyg样式(如hide()show()等),上传图片失效
- 使用sklearn优雅地进行数据挖掘【转】
- luogu[2093]零件分组
- 【云计算】docker daemon如何提供Restful的API
- SQL 查询45题
- 转载---linux运维相关
- iOS经常使用类别
- 如何恢复未释放租约的HDFS文件
- SSM框架开发web项目系列(一) 环境搭建篇
- Android中Sqlite数据库进行增删改查
- C# 利用SharpZipLib生成压缩包
- Why Random Initialization in Neural Network?
- 来啊踩fastjson打印入参导致业务跑偏的坑
- SQL Server索引维护
- Java集合框架之一:ArrayList源码分析
- ORB-SLAM2(4) 离线双目数据测试
- ASIHTTPRequest 详解, http 请求终结者
- 不包含数据和字母的Webshell
热门文章
- linux随笔4
- python redis中blpop和lpop的区别
- TensorFlow——热身运动:简单的线性回归
- [uiautomator篇][9]遇到问题
- [错误处理]: How to deal with chrome failing to launch GPU process
- Unity3D - UGUI的手动搭建
- CodeForces 232E.Quick Tortoise
- 慕课爬虫实战 爬取百度百科Python词条相关1000个页面数据
- git超详细教程【转】
- HRBUST 2078:糖果(模拟,贪心)