-
Notifications
You must be signed in to change notification settings - Fork 0
/
101. Symmetric Tree.cpp
67 lines (63 loc) · 1.72 KB
/
101. Symmetric Tree.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
// Recursive
class Solution {
public:
bool isSymmetric(TreeNode* root) {
vector<vector<TreeNode*>>v;
dfs(root, v, 0);
return check(v);
}
void dfs(TreeNode* root, vector<vector<TreeNode*>>& v, int level){
if(level == v.size()) v.push_back({});
v[level].push_back(root);
if(!root) return;
dfs(root->left, v, level + 1);
dfs(root->right, v, level + 1);
}
bool check(vector<vector<TreeNode*>>& v){
for(auto x: v){
int l = 0, r = x.size() - 1;
while(l < r){
auto a = x[l++];
auto b = x[r--];
if((!a || !b) && (a || b) || (a && b) && (a->val != b->val)) return false;
}
}
return true;
}
};
// Iterative
class Solution {
public:
bool isSymmetric(TreeNode* root) {
vector<vector<TreeNode*>>v;
queue<TreeNode*>cur, next;
cur.push(root);
int level = 0;
while(!cur.empty()){
auto p = cur.front();
cur.pop();
if(v.size() == level) v.push_back({});
v[level].push_back(p);
if(p){
next.push(p->left);
next.push(p->right);
}
if(cur.empty()){
level++;
swap(cur, next);
}
}
return check(v);
}
bool check(vector<vector<TreeNode*>>& v){
for(auto x: v){
int l = 0, r = x.size() - 1;
while(l < r){
auto a = x[l++];
auto b = x[r--];
if((!a || !b) && (a || b) || (a && b) && (a->val != b->val)) return false;
}
}
return true;
}
};