-
Notifications
You must be signed in to change notification settings - Fork 0
/
59_SymmetricalBinaryTree.cpp
134 lines (101 loc) · 2.36 KB
/
59_SymmetricalBinaryTree.cpp
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
# include <iostream>
# include <vector>
# include <cstdlib>
# include <queue>
using namespace std;
// definition of tree node
struct TreeNode
{
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
void dispaly_vec(vector<int> &vec)
{
for (int i = 0; i < vec.size(); i++)
cout << vec[i] << ' ';
cout << endl;
}
void dispaly_tree(TreeNode* root)
{
if (root == NULL)
return;
cout << root->val << ' ';
dispaly_tree(root->left);
dispaly_tree(root->right);
}
void Mirror(TreeNode *pRoot)
{
if (pRoot == NULL)
return;
// mirror left and right, then swap left and right
Mirror(pRoot->left);
Mirror(pRoot->right);
swap(pRoot->left, pRoot->right);
}
bool isSymmetrical(TreeNode *root1, TreeNode *root2)
{
if (root1 == NULL && root2 == NULL)
return true;
if (root1 == NULL || root2 == NULL)
return false;
if (root1->val == root2->val)
if (isSymmetrical(root1->left, root2->right) && isSymmetrical(root1->right, root2->left))
return true;
return false;
}
bool isSymmetrical_Recur(TreeNode* pRoot)
{
if (pRoot == NULL)
return true;
return isSymmetrical(pRoot->left, pRoot->right);
}
bool isSymmetrical(TreeNode* pRoot)
{
if (pRoot == NULL)
return true;
queue<TreeNode *> q1, q2;
TreeNode *p1 = NULL, *p2 = NULL;
q1.push(pRoot);
q2.push(pRoot);
while (!q1.empty() && !q2.empty())
{
p1 = q1.front();
p2 = q2.front();
q1.pop();
q2.pop();
if (p1 == NULL && p2 == NULL)
continue;
if (p1 == NULL || p2 == NULL)
return false;
if (p1->val != p2->val)
return false;
q1.push(p1->left);
q1.push(p1->right);
q2.push(p2->right);
q2.push(p2->left);
}
return true;
}
int main()
{
TreeNode *root = NULL, *p;
bool res;
// construct tree
root = new TreeNode(8);
root->left = new TreeNode(6);
root->right = new TreeNode(6);
p = root->left;
p->left = new TreeNode(5);
p->right = new TreeNode(7);
p = root->right;
p->left = new TreeNode(7);
p->right = new TreeNode(5);
dispaly_tree(root);
cout << endl;
// result
res = isSymmetrical(root);
cout << res << endl;
return 0;
}