当前位置:网站首页>【LeetCode】求根节点到叶节点数字之和
【LeetCode】求根节点到叶节点数字之和
2022-08-10 00:39:00 【LawsonAbs】
1.题目
2. 思想
递归
3. 代码
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def __init__(self):
self.res = 0
def sumNumbers(self, root: Optional[TreeNode]) -> int:
self.dfs(root,tmp=0)
return self.res
# 深搜找出所有叶节点
# tmp 表示根节点到当前节点的值
def dfs(self,root,tmp):
if root is None: # 如果是None,说明到头儿了
return
if root.left:
self.dfs(root.left,tmp*10 + root.val)
if root.right:
self.dfs(root.right,tmp*10 + root.val)
# 如果左右节点都是空,说明当前就是根节点
if root.left ==None and root.right==None:
self.res += (tmp*10 + root.val)
边栏推荐
- 【软考软件评测师】软件测试基础知识
- PEG derivative Biotin-PEG1-OH (cas: 95611-10-2, 2-biotinaminoethanol) advantage description
- Involved in PEG-Biotin (CAS: 1778736-18-7) Biotin-PEG4-OH is widely used in molecular target detection
- 小程序实现搜索功能续
- 【毕业设计】基于ESP32的在线墨水屏桌面摆件 -物联网 单片机 嵌入式
- win10重装系统后没声音怎么办?
- 宝塔实测-搭建LightPicture开源图床系统
- 【CAS:41994-02-9 |Biotinyl tyramide】Biotinyl tyramide price
- 03|Process Control
- c语言结构体、函数以及指针练习(简单通讯录)
猜你喜欢
02|运算符
基于SSM实现手机销售商城系统
Data storage - the C language
How to turn off system protection in Win11?How to turn off the system protection restore function?
【毕业设计】基于ESP32的在线墨水屏桌面摆件 -物联网 单片机 嵌入式
y92.第六章 微服务、服务网格及Envoy实战 -- Envoy基础(三)
What should I do if there is no sound after reinstalling the system in win10?
2022金九银十工作潮,怎么样才能成功跳槽面试拿到高薪呢?
assert利用蚁剑登录
DHCP——动态主机配置协议
随机推荐
3511. 倒水问题
【报错】ModuleNotFoundError: No module named ‘paramiko‘
How to activate the payment function on WeChat official account?
pytest:如何在测试中编写和报告断言
嵌入式Qt-实现两个窗口的切换
ASEMI整流桥GBJ1010参数,GBJ1010规格,GBJ1010封装
以太网PHY芯片LAN8720A芯片研究
R语言使用coxph函数构建生存分析回归模型,使用forestmodel包的forest_model函数可视化生存回归模型对应的森林图
Pagoda measurement - building LightPicture open source map bed system
Summary of basic operations of c language files
技术分享 | 接口自动化测试如何处理 Header cookie
Kubernetes YAML编写 讲解
【Grpc】简介
-Chess game-
GB28181 sip和RTSP(Real-Time Streaming Protocol)实时流控制协议
pyhton之问~~~~~if __name__ == ‘__main__‘:是什么?
Character Statistics Histogram
【无标题】
为什么字符串一旦创建就不可以改变?
D-Biotinol Involved by Biotin, CAS No: 53906-36-8 Specific Properties Description