当前位置:网站首页>【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)
边栏推荐
猜你喜欢
【CAS:41994-02-9 |Biotinyl tyramide】Biotinyl tyramide price
UI遍历的初步尝试
基于Web的疫情隔离区订餐系统
Aptos 深度解读:机遇、挑战与风险
CAS:851113-28-5 (Biotin-ahx-ahx-tyramine)
渗透测试与攻防对抗——漏洞扫描&逻辑漏洞(Part1)
C language structure, function and pointer exercise (simple address book)
这一次,话筒给你:向自由软件之父 Richard M. Stallman 提问啦!
Next.js获取路由参数及styled-jsx 的使用
CAS:851113-28-5 (生物素-ahx-ahx-酪胺)
随机推荐
Solidity 智能合约入门
数据建模已死,真的吗?
02| operator
Data storage - the C language
Win11怎么关闭系统保护功能?系统保护还原功能怎么关闭?
R语言使用coxph函数构建生存分析回归模型,使用forestmodel包的forest_model函数可视化生存回归模型对应的森林图
Interlay集成至Moonbeam,为网络带来interBTC和INTR
[obs] obsqsv11 hard coding and comparison with metartc codec
What should I do if there is no sound after reinstalling the system in win10?
有PEG-Biotin参与的(CAS:1778736-18-7)Biotin-PEG4-OH广泛用于分子靶点检测
Pyscript,创建一个能执行crud操作的网页应用
365天挑战LeetCode1000题——Day 052 逐步求和得到正数的最小值 贪心
DHCP——动态主机配置协议
03|流程控制
无js实现弹出层效果
Quick responsiveness intelligent/smart responsiveness of polyethylene glycol type nano/reduction response hydrogels research and preparation
Koa中间件next实现
-向量点积-
微信账户体系科普:什么是UnionId、OpenId与wxopenid?
什么是一网统管?终于有人讲明白了