-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSymmetric Tree__dfs.cpp
77 lines (62 loc) · 1.19 KB
/
Symmetric Tree__dfs.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
69
70
71
72
73
74
75
76
77
/*
Symmetric Tree
Given a binary tree, check whether it is a mirror of itself (ie, symmetric around its center).
For example, this binary tree is symmetric:
1
/ \
2 2
/ \ / \
3 4 4 3
But the following is not:
1
/ \
2 2
\ \
3 3
*/
#include<iostream>
using namespace std;
//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 dfs(TreeNode *a, TreeNode *b)
{
if (!a && !b) return true; //¶¼Îª¿Õ
if (!a || !b) return false; //ÓÐÒ»¸ö²»Îª¿Õ
if (a->val != b->val)
return false;
return dfs(a->left, b->right) && dfs(a->right, b->left);
}
bool isSymmetric(TreeNode *root) {
if (!root)
return true;
return (dfs(root->left, root->right));
}
};
void main()
{
TreeNode Root(1);
TreeNode temp0(2);
TreeNode temp1(2);
TreeNode temp2(3);
TreeNode temp3(5);
TreeNode temp4(4);
TreeNode temp5(3);
Root.left = &temp0;
Root.right = &temp1;
Root.left->left = &temp2;
Root.left->right = &temp3;
Root.right->left = &temp4;
Root.right->right = &temp5;
Solution mySolu;
if (mySolu.isSymmetric(&Root))
cout << "yes" << endl;
else
cout << "no" << endl;
}