DFS回溯只在递归基回溯————leetcode112
Posted vector11248
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了DFS回溯只在递归基回溯————leetcode112相关的知识,希望对你有一定的参考价值。
# 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)
以上是关于DFS回溯只在递归基回溯————leetcode112的主要内容,如果未能解决你的问题,请参考以下文章