File tree

1 file changed

+114
-0
lines changed

1 file changed

+114
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,114 @@
1+
#User function Template for python3
2+
3+
'''
4+
class Node:
5+
def __init__(self,val):
6+
self.data = val
7+
self.left = None
8+
self.right = None
9+
'''
10+
class Solution:
11+
def hasPathSum(self,root, S):
12+
'''
13+
:param root: root of given tree.
14+
:param sm: root to leaf sum
15+
:return: true or false
16+
'''
17+
temp=0
18+
def helper(root,S,temp):
19+
if not root:
20+
return
21+
temp+=root.data
22+
if not root.left and not root.right:
23+
if temp==S:
24+
return True
25+
else:
26+
return False
27+
28+
return helper(root.left,S,temp) or helper(root.right,S,temp)
29+
return helper(root,S,temp)
30+
# code here
31+
32+
#{
33+
# Driver Code Starts
34+
#Initial Template for Python 3
35+
36+
from collections import deque
37+
# Tree Node
38+
class Node:
39+
def __init__(self, val):
40+
self.right = None
41+
self.data = val
42+
self.left = None
43+
44+
45+
# Function to Build Tree
46+
def buildTree(s):
47+
#Corner Case
48+
if(len(s)==0 or s[0]=="N"):
49+
return None
50+
51+
# Creating list of strings from input
52+
# string after spliting by space
53+
ip=list(map(str,s.split()))
54+
55+
# Create the root of the tree
56+
root=Node(int(ip[0]))
57+
size=0
58+
q=deque()
59+
60+
# Push the root to the queue
61+
q.append(root)
62+
size=size+1
63+
64+
# Starting from the second element
65+
i=1
66+
while(size>0 and i<len(ip)):
67+
# Get and remove the front of the queue
68+
currNode=q[0]
69+
q.popleft()
70+
size=size-1
71+
72+
# Get the current node's value from the string
73+
currVal=ip[i]
74+
75+
# If the left child is not null
76+
if(currVal!="N"):
77+
78+
# Create the left child for the current node
79+
currNode.left=Node(int(currVal))
80+
81+
# Push it to the queue
82+
q.append(currNode.left)
83+
size=size+1
84+
# For the right child
85+
i=i+1
86+
if(i>=len(ip)):
87+
break
88+
currVal=ip[i]
89+
90+
# If the right child is not null
91+
if(currVal!="N"):
92+
93+
# Create the right child for the current node
94+
currNode.right=Node(int(currVal))
95+
96+
# Push it to the queue
97+
q.append(currNode.right)
98+
size=size+1
99+
i=i+1
100+
return root
101+
102+
103+
if __name__ == '__main__':
104+
test_cases = int(input())
105+
for cases in range(test_cases):
106+
s=input()
107+
root = buildTree(s)
108+
sum=int(input())
109+
if Solution().hasPathSum(root, sum)==True:
110+
print(1)
111+
else:
112+
print(0)
113+
114+
# } Driver Code Ends

0 commit comments

Comments
 (0)