当前位置:网站首页>[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)
边栏推荐
- GB28181 sip和RTSP(Real-Time Streaming Protocol)实时流控制协议
- 基于Web的疫情隔离区订餐系统
- 快速响应性智能型/智能响应性聚乙二醇纳米/还原响应型水凝胶的研究与制备
- -象棋比赛-
- el-input保留一位小数点
- What should I do if there is no sound after reinstalling the system in win10?
- 【ROS2原理10】Interface数据的规定
- 【CAS:41994-02-9 |Biotinyl tyramide】Biotinyl tyramide price
- C language pointer practice questions
- 【无标题】
猜你喜欢
随机推荐
Pagoda measurement - building LightPicture open source map bed system
R语言使用cox函数构建生存分析回归模型、使用subgroupAnalysis进行亚组分析并可视化森林图
微信小程序tab切换时保存checkbox状态
Biotin-Cy2 Conjugate,生物素-Cy2 偶联物_Cy2 生物素偶联物
[obs] obsqsv11 hard coding and comparison with metartc codec
Stanford CS143 Speed Pass PA1 Tutorial
CAS:183896-00-6 (Biotin-PEG3-C3-NH2) PEG derivative
-Chess game-
快速响应性智能型/智能响应性聚乙二醇纳米/还原响应型水凝胶的研究与制备
宽带由20M换为100M
防勒索病毒现状分析
Interlay集成至Moonbeam,为网络带来interBTC和INTR
C language structure, function and pointer exercise (simple address book)
-向量点积-
移动终端数据业务高安全通信方案研究
pyhton之问~~~~~if __name__ == ‘__main__‘:是什么?
3438. 数制转换
分析 20 个 veToken 生态系统协议 这种代币模型为何受欢迎?
-Knight Parade-
【报错】ModuleNotFoundError: No module named ‘paramiko‘









