Leaderboard
Showing:
Handle Score
@Ibrahim Nash 6381
@blackshadows 6329
@mb1973 5388
@Quandray 5231
@akhayrutdinov 5111
@saiujwal13083 4510
@sanjay05 3762
@marius_valentin_dragoi 3522
@sushant_a 3459
@verma_ji 3357
@KshamaGupta 3318
Complete Leaderboard
Root to leaf path sum
Easy Accuracy: 36.24% Submissions: 56815 Points: 2

Given a binary tree and an integer S, check whether there is root to leaf path with its sum as S.

Example 1:

Input:
Tree = 
            1
          /   \
        2      3
S = 2

Output: 0

Explanation:
There is no root to leaf path with sum 2.

Example 2:

Input:
Tree = 
            1
          /   \
        2      3
S = 4

Output: 1

Explanation:
The sum of path from leaf node 3 to root 1 is 4.


Your Task:  
You dont need to read input or print anything. Complete the function hasPathSum() which takes root node and target sum S as input parameter and returns true if path exists otherwise it returns false.


Expected Time Complexity: O(N)
Expected Auxiliary Space: O(height of tree)

Constraints:
1 ≤ N ≤ 10^4
1 ≤ S ≤ 10^6

to report an issue on this page.

Editorial

We strongly recommend solving this problem on your own before viewing its editorial. Do you still want to view the editorial?

Yes

All Submissions

My Submissions:

Login to access your submissions.

Root to leaf path sum

Output Window