# Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None # class Solution: # def hasPathSum(self, root, sum): # """ # :type root: TreeNode # :type sum: int # :rtype: bool # """ class Solution: res = False def hasPathSum(self, root, sum): """ :type root: TreeNode :type sum: int :rtype: bool """ if root is None: return False self.dfs2(root,0,sum) return self.res def dfs2(self, node, temp_sum, sum): temp_sum += node.val if not node.left and not node.right: if temp_sum == sum: self.res = True return temp_sum -= node.val return if node.left: self.dfs2(node.left,temp_sum,sum) if node.right: self.dfs2(node.right,temp_sum,sum)
原文地址:https://www.cnblogs.com/vector11248/p/9712554.html
时间: 2024-11-17 17:27:56