-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path111SymmetricTree.cpp
More file actions
62 lines (51 loc) · 1.44 KB
/
Copy path111SymmetricTree.cpp
File metadata and controls
62 lines (51 loc) · 1.44 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
#include<iostream>
#include<queue>
using namespace std;
///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 == nullptr) return true;
queue<TreeNode*>q;
q.push(root->left);
q.push(root->right);
while(!q.empty()){
TreeNode* a = q.front(); q.pop();
TreeNode* b = q.front(); q.pop();
if(!a && !b) continue;
if(!a || !b) return false;
if(a->val != b->val) return false;
q.push(a->left); q.push(b->right);
q.push(a->right); q.push(b->left);
}
return true;
}
};
int main() {
/*
1
/ \
2 2
/ \ / \
3 4 4 3
*/
TreeNode* root = new TreeNode(1);
root->left = new TreeNode(2);
root->right = new TreeNode(2);
root->left->left = new TreeNode(3);
root->left->right = new TreeNode(4);
root->right->left = new TreeNode(4);
root->right->right = new TreeNode(3);
Solution sol;
cout << boolalpha;
cout << "Is Symmetric: " << sol.isSymmetric(root) << endl;
return 0;
}