Skip to content

Commit

Permalink
(二叉树)路径和
Browse files Browse the repository at this point in the history
  • Loading branch information
rinwf committed Dec 11, 2018
1 parent 4cc9e98 commit eb555c5
Showing 1 changed file with 40 additions and 0 deletions.
40 changes: 40 additions & 0 deletions Path Sum.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
# 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
"""

def dfs(root, tar):
if not root:
return
if root.val == tar and root.left is None and root.right is None:
global res
res = True
# print(23, res)
return
dfs(root.left, tar - root.val)
dfs(root.right, tar - root.val)

if not root:
return False
res = False
dfs(root, sum)
return res


root = TreeNode(5)
root.left = TreeNode(4)
root.left.left = TreeNode(11)
root.left.left.right = TreeNode(2)

print(Solution().hasPathSum(root, 22))

0 comments on commit eb555c5

Please sign in to comment.