-
Notifications
You must be signed in to change notification settings - Fork 0
/
GFG Check if all levels of two trees are anagrams or not
111 lines (44 loc) · 1.53 KB
/
GFG Check if all levels of two trees are anagrams or not
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
class Solution{
public:
bool areAnagrams(Node *root1, Node *root2)
{
if(root1==NULL && root2==NULL)
return true;
if(root1==NULL || root2==NULL)
return false;
queue<Node*>q1,q2;
q1.push(root1);
q2.push(root2);
unordered_map<int,int>m;
while(q1.size() > 0 && q2.size()>0){
int n1=q1.size();
int n2=q2.size();
while(n1){
auto front = q1.front();
q1.pop();
m[front->data]++;
if(front->left)
q1.push(front->left);
if(front->right)
q1.push(front->right);
n1--;
}
while(n2){
auto front =q2.front();
q2.pop();
if(m.find(front->data)==m.end())
return false;
m[front->data]--;
if(m[front->data]==0)
m.erase(front->data);
if(front->left)
q2.push(front->left);
if(front->right)
q2.push(front->right);
n2--;
}
}
if(m.size()==0)
return true;
return false;
}