-
Notifications
You must be signed in to change notification settings - Fork 14
/
tree_isSymmetric.cpp
47 lines (39 loc) · 1.07 KB
/
tree_isSymmetric.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
#include <iostream>
using namespace std;
struct Node
{
int key;
Node *left, *right;
};
struct Node* newNode(int key)
{
struct Node * node = new Node;
node->key = key;
node->left = node->right = nullptr;
return node;
}
bool isTreeSymmetric_helper(Node * root1, Node * root2)
{
if (root1 == nullptr && root2 == nullptr) {return true;}
else if (root1 == nullptr || root2 == nullptr) {return false;}
if (root1->key != root2->key) {return false;}
return isTreeSymmetric_helper(root1->left, root2->right) && isTreeSymmetric_helper(root1->right, root2->left);
}
bool isTreeSymmetric(Node * root)
{
return isTreeSymmetric_helper(root, root);
}
int main()
{
//create a tree
Node *root = newNode(1);
root->left = newNode(2);
root->right = newNode(2);
root->left->left = newNode(3);
root->left->right = newNode(4);
root->right->left = newNode(4);
root->right->right = newNode(3);
cout << "Q: Is tree symmetric?" << endl;
isTreeSymmetric(root) ? cout << "A: yes" << endl : cout <<"A: no" << endl;
return 0;
}