-
Notifications
You must be signed in to change notification settings - Fork 22
/
Copy pathcounting number of subtrees with given sum
72 lines (58 loc) · 1.46 KB
/
counting number of subtrees with given sum
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
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
/*
Given a binary tree containing N+1 with N edges nodes and an integer X. Your task is to complete the function countSubtreesWithSumX()
that returns the count of the number of subtress having total node’s data sum equal to a value X.
Example: For the tree given below:
5
/ \
-10 3
/ \ / \
9 8 -4 7
Subtree with sum 7:
-10
/ \
9 8
and one node 7.
Input:
First line of input contains number of testcases T. For each testcase, first line of input contains number of edges in the tree. Next
line contains information as X Y L or X Y R which means Y is on the left of X or Y is on the right of X respectively. Last line contains
sum.
Output:
For each test case count the number of subtrees with given sum.
Your Task:
The task is to complete the function countSubtreesWithSumX() which check if there exists a subtree with sum x.
Constraints:
1 <= T <= 103
1 <= N <= 103
-103 <= Node Value <= 103
Example:
Input:
2
6
5 -10 L 5 3 R -10 9 L -10 8 R 3 -4 L 3 7 R
7
2
1 2 L 1 3 R
5
Output:
2
0
Explanation:
Testcase 1: Subtrees with sum 7 are [9, 8, -10] and [7].
*/
int value(Node* root,int x,int &count)
{
if(root==NULL)
return 0;
int s1=value(root->left,x,count);
int s2=value(root->right,x,count);
if(s1+s2+root->data==x)
count++;
}
int countSubtreesWithSumX(Node* root, int x)
{
if(root==NULL)
return 0;
int count=0;
value(root,x,count);
return count;
}