-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path07_PathSum.py
More file actions
29 lines (24 loc) · 1.01 KB
/
07_PathSum.py
File metadata and controls
29 lines (24 loc) · 1.01 KB
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
# Question link - https://leetcode.com/problems/path-sum/description/?envType=study-plan-v2&envId=top-interview-150
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def hasPathSum(self, root: Optional[TreeNode], targetSum: int) -> bool:
# For this , problem we need to travere a Tree in Inorder DFS
# So implementing the helper function
def Dfs(node , curSum):
# Base case
if not node:
return False
# If node , then calculate the sum
curSum += node.val
# If a leaf node
if not node.left and not node.right:
# Just return boolean True and false
return curSum == targetSum
# If not leaf , call for both subtrees
return ( Dfs(node.left, curSum) or Dfs(node.right, curSum))
return Dfs(root, 0)