-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathLC_101_Tree_Symmetric.cpp
68 lines (52 loc) · 1.78 KB
/
LC_101_Tree_Symmetric.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
/* https://leetcode.com/problems/symmetric-tree/
* Given the root of a binary tree, check whether it is a mirror of itself (i.e., symmetric around its center).
*/
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
bool isSymmetric(TreeNode* root) {
if(!root) return true;
//return (isSym(root->left, root->right)); // recursive solution
return isSym_BFS(root); // iterative solution
}
bool isSym(TreeNode* t1, TreeNode* t2){
if (t1 == nullptr && t2 == nullptr)
return true;
if(t1 == nullptr || t2 ==nullptr)
return false;
if(t1->val == t2->val)
return (isSym(t1->left, t2->right) && isSym(t1->right, t2->left));
else
return false;
}
bool isSym_BFS(TreeNode *t){
if (t->left == nullptr && t->right == nullptr)
return true;
queue<TreeNode *> q;
q.push(t->left);
q.push(t->right);
while(!q.empty())
{
TreeNode *leftc = q.front(); q.pop();
TreeNode *rightc = q.front(); q.pop();
if(!leftc && !rightc) continue;
if(!leftc || !rightc) return false;
if(leftc->val != rightc->val) return false;
q.push(leftc->left);
q.push(rightc->right);
q.push(leftc->right);
q.push(rightc->left);
}
return true;
}
};