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