-
Notifications
You must be signed in to change notification settings - Fork 0
/
Symmetric Tree
46 lines (46 loc) · 1.14 KB
/
Symmetric Tree
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
/**
* Definition for binary tree
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
bool isSymmetric(TreeNode *root) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
vector<int> pre;
vector<int> post;
preTrav(pre, root);
postTrav(post, root);
return isSame(pre, post);
}
void preTrav(vector<int> & pre, TreeNode* r){
if(r == NULL)
return;
else{
preTrav(pre, r->right);
pre.push_back(r->val);
preTrav(pre, r->left);
}
}
void postTrav(vector<int> & post, TreeNode* r){
if(r == NULL)
return;
else{
postTrav(post, r->left);
post.push_back(r->val);
postTrav(post, r->right);
}
}
bool isSame(vector<int> & pre, vector<int> & post){
for(int i = 0; i < post.size(); i++){
if(pre[i] != post[i])
return false;
}
return true;
}
};