Greetings Kind Regards There were two typing errors i.e. a missing terminating semi-colon in the declaration of
isTreeSymmetric
and a colon in the line above the third
delete
in main Why did your compiler not tell you of these as mine did Also a misspelling of "symmetric" Other than that the code below worked for me w/ the output below -
Cheerio
#include <iostream>
using namespace std;
struct Node {
int ID;
Node* left, * right;
Node(int id) { ID = id; left = right = nullptr; }
};
Node* gRoot1 = nullptr, * gRoot2 = nullptr;
Node* createTree();
void setAllIDareEqual(Node* Z);
bool areTreesIdentical(Node* a, Node* b);
bool isTreeSymmetric(Node* a, Node* b);
int main() {
gRoot1 = createTree(); gRoot2 = createTree();
cout << "\n\nBoth are "
<< (!areTreesIdentical(gRoot1, gRoot2) ? "NOT " : "") << "identical.";
delete gRoot2->right->right->left;
gRoot2->right->right->left = nullptr;
cout << "\n\nBoth are "
<< (!areTreesIdentical(gRoot1, gRoot2) ? "NOT " : "") << "identical.";
delete gRoot1->right->right->left;
gRoot1->right->right->left = nullptr;
cout << "\n\nBoth are "
<< (!areTreesIdentical(gRoot1, gRoot2) ? "NOT " : "") << "identical.";
cout << "\n\nTree is "
<< (!isTreeSymmetric(gRoot1, gRoot1) ? "NOT " : "") << "symmetric.";
delete gRoot1->right->right->right; gRoot1->right->right->right = nullptr;
cout << "\n\nTree is "
<< (!isTreeSymmetric(gRoot1, gRoot1) ? "NOT " : "") << "Symmetric.";
setAllIDareEqual(gRoot1);
cout << "\n\nTree is "
<< (!isTreeSymmetric(gRoot1, gRoot1) ? "NOT " : "") << "Symmetric.";
cout << "\n\n\n";
return 0;
}
Node* createTree() {
Node* p[12];
for (int i = 1; i <= 11; i++) p[i] = new Node(i);
p[1]->left = p[2]; p[1]->right = p[3];
p[2]->left = p[4]; p[2]->right = p[5];
p[3]->left = p[6]; p[3]->right = p[7];
p[5]->left = p[8];
p[6]->right = p[9];
p[7]->left = p[10]; p[7]->right = p[11];
return p[1];
}
void setAllIDareEqual(Node* Z) {
if (Z) {
Z->ID = 99;
setAllIDareEqual(Z->left);
setAllIDareEqual(Z->right);
}
}
bool areTreesIdentical(Node* a, Node* b) {
if (a == NULL && b == NULL) return 1;
if (a != NULL && b != NULL)
return (a->ID == b->ID && areTreesIdentical(a->left, b->left) && areTreesIdentical(a->right, b->right));
return 0;
}
bool isTreeSymmetric(Node* a, Node* b) {
if (a == NULL && b == NULL) return true;
if (a && b && a->ID == b->ID)
return isTreeSymmetric(a->left, b->right) && isTreeSymmetric(a->right, b->left);
return false;
}
Both are identical.
Both are NOT identical.
Both are identical.
Tree is NOT symmetric.
Tree is NOT Symmetric.
Tree is Symmetric.