# LeetCode112.路径总和

version 1

# Definition for a binary tree node.
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None

class Solution:
def __init__(self):
self.hasFind = False
self.target = None

def hasPathSum(self, root, sum):
"""
:type root: TreeNode
:type sum: int
:rtype: bool
"""
if not root: return False
self.target = sum
self.dfs(root, root.val)
return self.hasFind

def dfs(self, bt: TreeNode, s):
if self.hasFind:
return
if s == self.target and not bt.left and not bt.right:
self.hasFind = True
return
if bt.left:
self.dfs(bt.left, s + bt.left.val)
if bt.right:
self.dfs(bt.right, s + bt.right.val)


version 2

# 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
"""
if not root: return False
elif root.val == sum and not root.left and not root.right:
return True
return self.hasPathSum(root.left, sum - root.val) or self.hasPathSum(root.right, sum - root.val)


©️2019 CSDN 皮肤主题: 大白 设计师: CSDN官方博客