树的遍历 | 路径总和
Given a binary tree and a sum, determine if the tree has a root-to-leaf path such that adding up all the values along the path equals the given sum.
Note: A leaf is a node with no children.
Example:
Given the below binary tree and sum = 22,
5
/ \
4 8
/ / \
11 13 4
/ \ \
7 2 1
return true, as there exist a root-to-leaf path 5->4->11->2 which sum is 22.
思路1: 遍历
在遍历的过程中,保留从根节点到当前节点的值,在访问到某个节点时,如果该节点为叶子节点,且sum = 0,则返回True
class Solution(object):
def hasPathSum(self, root, sum):
"""
:type root: TreeNode
:type sum: int
:rtype: bool
dfs
"""
if root is None:
return False
root.sum = sum - root.val
stack = [root]
while len(stack):
while root:
left = root.left
if left:
left.sum = root.sum - left.val
stack.append(left)
root = left
root = stack.pop()
if root:
if root.sum == 0 and root.left is None and root.right is None:
return True
if root.right:
right = root.right
right.sum = root.sum - right.val
stack.append(right)
root = right
return False
思路2: 递归,
递归判断左子树或右子树是否存在 sum - root.val 的路径。
class Solution(object):
def hasPathSum(self, root, sum):
"""
:type root: TreeNode
:type sum: int
:rtype: bool
dfs
"""
if root is None:
return False
sum = sum - root.val
if sum == 0 and root.left == None and root.right == None:
return True
else:
return self.hasPathSum(root.left, sum) or self.hasPathSum(root.right, sum)
【推荐】还在用 ECharts 开发大屏?试试这款永久免费的开源 BI 工具!
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 软件产品开发中常见的10个问题及处理方法
· .NET 原生驾驭 AI 新基建实战系列:向量数据库的应用与畅想
· 从问题排查到源码分析:ActiveMQ消费端频繁日志刷屏的秘密
· 一次Java后端服务间歇性响应慢的问题排查记录
· dotnet 源代码生成器分析器入门
· 互联网不景气了那就玩玩嵌入式吧,用纯.NET开发并制作一个智能桌面机器人(四):结合BotSharp
· 软件产品开发中常见的10个问题及处理方法
· Vite CVE-2025-30208 安全漏洞
· MQ 如何保证数据一致性?
· 《HelloGitHub》第 108 期
2018-02-14 Python tutorial阅读之函数的定义与使用
2018-02-14 LeetCode:3Sum