-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path101_gp.cpp
66 lines (58 loc) · 1.57 KB
/
101_gp.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
// recursive
class Solution {
public:
bool isSymmetric(TreeNode* root) {
if(!root)
return true;
return helper(root->left, root->right);
}
bool helper(TreeNode* node1, TreeNode* node2){
if(node1 == NULL && node2 == NULL){
return true;
}
if(node1 == NULL && node2 != NULL){
return false;
}
if(node1 != NULL && node2 == NULL){
return false;
}
if(node1->val != node2-> val){
return false;
}
return node1->val == node2-> val && helper(node1->left, node2->right) && helper(node1->right, node2->left);
}
};
//iterative
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
bool isSymmetric(TreeNode* root) {
if(!root)
return true;
queue<TreeNode*> bfs;
bfs.push(root);
bfs.push(root);
while(bfs.size() > 0){
TreeNode* t1 = bfs.front();
bfs.pop();
TreeNode* t2 = bfs.front();
bfs.pop();
if (t1 == NULL && t2 == NULL) continue;
if (t1 == NULL || t2 == NULL) return false;
if (t1->val != t2->val) return false;
bfs.push(t1->left);
bfs.push(t2->right);
bfs.push(t1->right);
bfs.push(t2->left);
}
return true;
}
};