-
Notifications
You must be signed in to change notification settings - Fork 0
/
SymetricTree.cpp
41 lines (40 loc) · 1.14 KB
/
SymetricTree.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
//recursive
class Solution {
public:
bool isSymmetric(TreeNode* root) {
if(!root) return true;
return helper(root->left,root->right);
}
bool helper(TreeNode* p,TreeNode* q){
if(!p && !q) return true;
else if(!p || !q) return false;
if(p->val != q->val) return false;
return helper(p->left,q->right) && helper(p->right,q->left);
}
};
//iterative
class Solution {
public:
bool isSymmetric(TreeNode* root) {
if(!root) return true;
queue<TreeNode*>q;
q.push(root->left);
q.push(root->right);
while(!q.empty()){
TreeNode* node1 = q.front();
q.pop();
TreeNode* node2 = q.front();
q.pop();
if(!node1 && node2) return false;
if(!node2 && node1) return false;
if(node1 && node2){
if(node1->val != node2->val) return false;
q.push(node1->left);
q.push(node2->right);
q.push(node1->right);
q.push(node2->left);
}
}
return true;
}
};