# 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 hasPathSum(self, root: Optional[TreeNode], targetSum: int) -> bool:
# currentSum = 0
# result = self.traversal(root, currentSum, targetSum)
# if result == 0:
# return True
# else:
# return False
# def traversal(self, root, currentSum, targetSum):
# if not root:
# return currentSum
# currentSum += root.val
# if currentSum > targetSum: #当加上当前节点超过目标值的时候 直接返回,不再往下递归了
# currentSum -= root.val
# return currentSum
# elif currentSum < targetSum:
# sum1 = self.traversal(root.left, currentSum, targetSum)
# sum2 = self.traversal(root.right, currentSum, targetSum)
# if sum1 == 0 or sum2 == 0:
# return 0
# else:
# currentSum-= root.val
# return currentSum
# else:
# if not root.left and not root.right:
# return 0
# else:
# currentSum-= root.val
# return currentSum
# 上面不对
# if not root:
# return False
# return self.traversal(root, targetSum - root.val)
# def traversal(self, root, count):
# if not root.left and not root.right and count == 0:
# return True
# if not root.left and not root.right:
# return False
# if root.left:
# count -= root.left.val
# if self.traversal(root.left, count):
# return True
# else:
# count += root.left.val
# if root.right:
# count -= root.right.val
# if self.traversal(root.right, count):
# return True
# else:
# count += root.right.val
# return False
# #以上是可以跑通的但是代码有冗余
self.traversal(root, targetSum)
return self.symbol
def __init__(self):
self.symbol = False
def traversal(self, node, count):
if self.symbol == True:
return
if not node:
return
count -= node.val
if not node.left and not node.right and count == 0:
self.symbol = True
self.traversal(node.left, count)
self.traversal(node.right, count)
# 以上是正确且简洁的版本
112. 路径总和
于 2024-01-17 00:19:13 首次发布
文章讲述了如何在给定二叉树节点定义和类Solution中实现hasPathSum方法,用于判断是否存在从根节点到叶子节点的路径,其和等于目标值。初始版本包含冗余代码,但经过优化后的traversal函数更为简洁且有效。
摘要由CSDN通过智能技术生成