-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path101.cpp
More file actions
79 lines (62 loc) · 1.62 KB
/
101.cpp
File metadata and controls
79 lines (62 loc) · 1.62 KB
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
/*
* Written by Nitin Kumar Maharana
* nitin.maharana@gmail.com
*/
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
//Iterative Solution.
class Solution {
queue<TreeNode*> q1, q2;
public:
bool isSymmetric(TreeNode *l, TreeNode *r)
{
q1.push(l);
q2.push(r);
TreeNode *l1, *h1;
while(!q1.empty() && !q2.empty())
{
l1 = q1.front();
h1 = q2.front();
q1.pop();
q2.pop();
if(!l1 && !h1)
continue;
if(!l1 || !h1 || (l1->val != h1->val))
return false;
q1.push(l1->left);
q1.push(l1->right);
q2.push(h1->right);
q2.push(h1->left);
}
return true;
}
bool isSymmetric(TreeNode* root) {
if(!root)
return true;
return isSymmetric(root->left, root->right);
}
};
//Recursive Solution.
class Solution {
public:
bool isSymmetric(TreeNode* l, TreeNode* r)
{
if(!l && !r)
return true;
if((!l || !r || (l->val != r->val))
return false;
return (isSymmetric(l->left, r->right) && isSymmetric(l->right, r->left));
}
bool isSymmetric(TreeNode* root) {
if(!root)
return true;
return isSymmetric(root->left, root->right);
}
};