-
Notifications
You must be signed in to change notification settings - Fork 28
/
Copy pathQ501-MirrorTree
84 lines (75 loc) · 1.74 KB
/
Q501-MirrorTree
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
// C++ program to check if two trees are mirror
// of each other
#include<iostream>
using namespace std;
/* A binary tree node has data, pointer to
left child and a pointer to right child */
struct Node
{
int data;
Node* left, *right;
};
/* Given two trees, return true if they are
mirror of each other */
/*As function has to return bool value instead integer value*/
bool areMirror(Node* a, Node* b)
{
/* Base case : Both empty */
if (a==NULL && b==NULL)
return true;
// If only one is empty
if (a==NULL || b == NULL)
return false;
/* Both non-empty, compare them recursively
Note that in recursive calls, we pass left
of one tree and right of other tree */
return a->data == b->data &&
areMirror(a->left, b->right) &&
areMirror(a->right, b->left);
}
/* Helper function that allocates a new node */
Node* newNode(int data)
{
Node* node = new Node;
node->data = data;
node->left = node->right = NULL;
return(node);
}
/* Driver program to test areMirror() */
int main()
{
Node *a = newNode(1);
Node *b = newNode(1);
int n;
cin>>n;
for(int i=0;i<n-1;i++)
{
char p,q,r;
cin>>p>>q>>r;
if(i==0){
a=newNode(p-48);
}
if(r=='L'){
a->left = newNode(q-48);
}
else{
a->right = newNode(q-48);
}
}
for(int i=0;i<n-1;i++)
{
char p,q,r;
cin>>p>>q>>r;
if(i==0){
b=newNode(p-48);
}
if(r=='L'){
b->left = newNode(q-48);
}
else{
b->right = newNode(q-48);
}
}
areMirror(a, b)? cout << "yes" : cout << "no";
return 0;
}