-
Notifications
You must be signed in to change notification settings - Fork 22
/
check if subtree
140 lines (105 loc) · 2.72 KB
/
check if subtree
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
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
/*
Given two binary trees with head reference as T and S having at most N nodes. The task is to check if S is present as subtree in T.
A subtree of a tree T1 is a tree T2 consisting of a node in T1 and all of its descendants in T1.
Example:
S: 10
/ \
4 6
/
30
T: 26
/ \
10 3
/ \ \
4 6 3
/
30
In above example S is subtree of T.
Please note that subtree has to be having same leaves non leaves.
10
/
20
For example, above tree is not subtree of
10
/ \
20 50
/ \
30 40
But a subtree of
30
/ \
10 50
/
20
Input Format:
First line of input contains number of testcases T. For each testcase, there will be 4 lines, first of which containing the number of
edges (between two nodes) in the S tree. Next line contains N pairs (considering a and b) with a 'L' (means node b on left of a) or 'R'
(means node b on right of a) after a and b. The next two lines of every test case contain details of tree T
Output Format:
For each testcase, there will be a single line containing 0 or 1, depending on the input.
Your Task:
Complete the function isSubtree() that takes two nodes as parameter and returns true or false.
Constraints:
1 <= T <= 30
1 <= N <= 103
Example:
Input:
3
1
3 4 L
3
1 2 L 1 3 R 3 4 L
5
26 10 L 10 20 L 10 30 R 20 40 L 20 60 R
5
26 10 L 10 20 L 10 30 R 20 40 L 20 60 R
3
10 4 L 10 6 R 4 30 R
6
26 10 L 26 3 R 10 4 L 10 6 R 6 25 R 3 3 R
Output:
1
1
0
Explanation:
Testcase 3:
Structure of tree:
10 4 L 10 6 R 4 30 R
10 is root node of tree. Left child of 10 is 4 and right child of 10 is 6. Right child of 4 is 30.
*/
void fillInorder(Node* root, char arr[], int& i)
{
if (root == NULL) {
arr[i++] = '$';
return;
}
fillInorder(root->left, arr, i);
arr[i++] = root->data;
fillInorder(root->right, arr, i);
}
void fillPreOrder(Node* root, char arr[], int& i)
{
if (root == NULL) {
arr[i++] = '$';
return;
}
arr[i++] = root->data;
fillPreOrder(root->left, arr, i);
fillPreOrder(root->right, arr, i);
}
bool isSubtree(Node* t, Node* s) {
if(s==NULL) return true;
if(t==NULL) return false;
int m=0,n=0;
char inT[MAX] , inS[MAX];
fillInorder(t,inT,m);
fillInorder(s,inS,n);
inT[m]='\0'; inS[n]='\0';
if(strstr(inT, inS) == NULL) return false;
m=0,n=0;
char preT[MAX] , preS[MAX];
fillPreOrder(t,preT,m);
fillPreOrder(s,preS,n);
preT[m]='\0'; preS[n]='\0';
return (strstr(preT, preS) != NULL);
}