-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy path对称二叉树.cpp
63 lines (56 loc) · 1.11 KB
/
对称二叉树.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
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
#include <map>
#include <set>
#include <utility>
#include <unordered_map>
#include <functional>
using namespace std;
struct TreeNode {
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
class Solution {
public:
bool isSymmetric(TreeNode* root)
{
if (!root)
return true;
return isSymmetric(root->left, root->right);
}
private:
bool isSymmetric(TreeNode *left, TreeNode *right)
{
if (!left && !right)
return true;
if (!left || !right)
return false;
if (left->val != right->val)
return false;
return isSymmetric(left->left, right->right) && isSymmetric(left->right, right->left);
}
};
int main()
{
TreeNode node1(1);
TreeNode node2(2);
TreeNode node3(2);
TreeNode node4(3);
TreeNode node5(4);
TreeNode node6(4);
TreeNode node7(3);
node1.left = &node2;
node1.right = &node3;
node2.left = &node4;
node2.right = &node5;
node3.left = &node6;
node3.right = &node7;
Solution a;
cout << boolalpha << a.isSymmetric(&node1) << endl;
system("pause");
return 0;
}