-
Notifications
You must be signed in to change notification settings - Fork 306
/
Copy path437.py
40 lines (32 loc) · 893 Bytes
/
437.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
#!/usr/bin/python
# -*- coding: utf-8 -*-
# Author: Yu Zhou
# 437. Path Sum III
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def pathSum(self, root, sum):
"""
:type root: TreeNode
:type sum: int
:rtype: int
"""
# Edge Case:
if not root:
return 0
# Process
def dfs(root, sum):
count = 0
if not root:
return 0
if root.val == sum:
count += 1
count += dfs(root.left, sum - root.val)
count += dfs(root.right, sum -root.val)
return count
# Recursion
return dfs(root,sum) + self.pathSum(root.left, sum) + self.pathSum(root.right, sum)