-
Notifications
You must be signed in to change notification settings - Fork 1
/
Symmetric Tree.cpp
68 lines (66 loc) · 1.75 KB
/
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
68
/**
* 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 isSame(TreeNode* a,TreeNode* b)
{
if(a==NULL && b==NULL)
return true;
if(a==NULL || b==NULL)
return false;
return((a->val == b->val) && isSame(a->left,b->right) && isSame(a->right,b->left));
}
bool isSymmetric(TreeNode* root) {
/*
TreeNode* temp=root;
if(root!=NULL)
return isSame(temp->left,temp->right);
else
return true;*/
if(root==NULL)
return true;
queue<TreeNode*> q;
q.push(root);
q.push(NULL);
stack<TreeNode*> stk;
stk.push(root);
while(!q.empty())
{
TreeNode* temp=q.front();
q.pop();
TreeNode* tempy=stk.top();
stk.pop();
if(temp==NULL)
{
if(!q.empty())
q.push(NULL);
else
return true;
while(!stk.empty())
stk.pop();
}
else
{
if(temp->val!=tempy->val)
return false;
if(temp->left!=NULL)
{
q.push(temp->left);
stk.push(temp->left);
}
if(temp->right!=NULL)
{
q.push(temp->right);
stk.push(temp->right);
}
}
}
}
};