-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLeetCode_101_SymmetricTree.cpp
More file actions
89 lines (80 loc) · 1.82 KB
/
Copy pathLeetCode_101_SymmetricTree.cpp
File metadata and controls
89 lines (80 loc) · 1.82 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
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
/*
Given a binary tree, check whether it is a mirror of itself (ie, symmetric around its center).
For example, this binary tree [1,2,2,3,4,4,3] is symmetric:
1
/ \
2 2
/ \ / \
3 4 4 3
But the following [1,2,2,null,3,null,3] is not:
1
/ \
2 2
\ \
3 3
*/
/**
* 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 isSymmetricUtil( TreeNode *left, TreeNode *right ) {
if( left == NULL && right == NULL ) {
return true;
}
if( left == NULL || right == NULL ) {
return false;
}
if( left->val != right->val ) {
return false;
}
return ( isSymmetricUtil( left->left, right->right ) &&
isSymmetricUtil( left->right, right->left ) );
}
bool isSymmetric(TreeNode* root) {
if( !root ) {
return true;
}
return isSymmetricUtil( root->left, root->right );
}
};
class Solution {
public:
bool isSymmetric(TreeNode* root) {
if( !root ) {
return true;
}
queue<TreeNode*> left;
left.push( root->left );
queue<TreeNode*> right;
right.push( root->right );
TreeNode *leftCurr;
TreeNode *rightCurr;
while( ! left.empty() && ! right.empty() ) {
leftCurr = left.front();
left.pop();
rightCurr = right.front();
right.pop();
if( leftCurr == NULL && rightCurr == NULL ) {
continue;
}
if( leftCurr == NULL || rightCurr == NULL ) {
return false;
}
if( leftCurr->val != rightCurr->val ) {
return false;
}
left.push( leftCurr->left );
left.push( leftCurr->right );
right.push( rightCurr->right );
right.push( rightCurr->left );
}
return true;
}
};