码迷,mamicode.com
首页 > 其他好文 > 详细

DFS回溯只在递归基回溯————leetcode112

时间:2018-09-27 14:19:05      阅读:157      评论:0      收藏:0      [点我收藏+]

标签:回溯   one   nod   style   elf   treenode   leetcode   efi   bool   

# 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

标签:回溯   one   nod   style   elf   treenode   leetcode   efi   bool   

原文地址:https://www.cnblogs.com/vector11248/p/9712554.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!