-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path101_binary_tree_symmetry.cpp
More file actions
49 lines (43 loc) · 1.34 KB
/
101_binary_tree_symmetry.cpp
File metadata and controls
49 lines (43 loc) · 1.34 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
/**
* 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) {
deque<TreeNode*> deq;
if (!root)
return true;
deq.push_front(root->left);
deq.push_front(root->right);
while(!deq.empty()) {
// pop left-most and right-most items
auto left = deq.back();
auto right = deq.front();
deq.pop_back();
deq.pop_front();
// compare the items
// either both are nullptr or they store the same value
if (left && right) {
if (left->val != right->val)
return false;
} else if (!left && !right)
continue;
else
return false;
// push the child nodes left and right
deq.push_back(left->right);
deq.push_back(left->left);
deq.push_front(right->left);
deq.push_front(right->right);
}
return true;
}
};