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)
        
            

 

posted @ 2018-09-27 13:27  vector11248  阅读(171)  评论(0编辑  收藏  举报