当前位置:网站首页>[LeetCode] Find the sum of the numbers from the root node to the leaf node
[LeetCode] Find the sum of the numbers from the root node to the leaf node
2022-08-10 02:11: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
# A deep search finds all leaf nodes
# tmp Represents the value from the root node to the current node
def dfs(self,root,tmp):
if root is None: # 如果是None,Explanation is over
return
if root.left:
self.dfs(root.left,tmp*10 + root.val)
if root.right:
self.dfs(root.right,tmp*10 + root.val)
# If left and right nodes are empty,Indicates that it is currently the root node
if root.left ==None and root.right==None:
self.res += (tmp*10 + root.val)
边栏推荐
猜你喜欢

03|Process Control

assert利用蚁剑登录

Biotin-Cy2 Conjugate, Biotin-Cy2 Conjugate_Cy2 Biotin Conjugate

即时通讯开发如何撸一个WebSocket服务器

数据建模已死,真的吗?

PEG 衍生物Biotin-PEG1-OH(cas:95611-10-2,2-生物素氨基乙醇)优势说明

分析 20 个 veToken 生态系统协议 这种代币模型为何受欢迎?

渗透测试与攻防对抗——漏洞扫描&逻辑漏洞(Part1)

365 days challenge LeetCode1000 questions - Day 052 Step by step summation to get the minimum value of positive numbers Greedy

What should I do if there is no sound after reinstalling the system in win10?
随机推荐
[obs] obsqsv11 hard coding and comparison with metartc codec
高校就业管理系统设计与实现
R语言使用glm函数构建逻辑回归模型(logistic)、使用subgroupAnalysis函数进行亚组分析并可视化森林图
Stanford CS143 Speed Pass PA1 Tutorial
微信小程序tab切换时保存checkbox状态
Docker 面试题2则--取数据库连接数和docker-compose
什么是持续测试?
assert利用蚁剑登录
罗彻斯特大学 | 现在是什么序列?蛋白质序列的贝叶斯优化的预训练集成
字符统计柱状图
移动终端数据业务高安全通信方案研究
走出迷宫的最少步数2
Win7怎么把控制面板添加到右键菜单
3511. 倒水问题
el-input保留一位小数点
XSS详解及复现gallerycms字符长度限制短域名绕过
c语言文件基本操作总结
将string类对象中的内容格式化到字符串Buffer中时遇到的异常崩溃分析
@PostConsturct注解作用及特点
温度响应性纳米水凝胶光子品体/纤维素修饰荧光水凝胶/载脂质体水凝胶的制备方法