Skip to content

Commit 7a863d8

Browse files
committed
add is_symmetric in c++
1 parent 8269e85 commit 7a863d8

File tree

1 file changed

+63
-0
lines changed

1 file changed

+63
-0
lines changed

Trees/Binary Trees/is_symmetric.c++

Lines changed: 63 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,63 @@
1+
#include <iostream>
2+
3+
using namespace std;
4+
5+
// This is an input class. Do not edit.
6+
class BinaryTree {
7+
public:
8+
int Value;
9+
BinaryTree* Left;
10+
BinaryTree* Right;
11+
};
12+
13+
// SymmetricalTree checks if a binary tree is symmetrical.
14+
bool SymmetricalTree(BinaryTree* tree) {
15+
// Call the helper function to check if the left and right subtrees are mirrored.
16+
return treesAreMirrored(tree->Left, tree->Right);
17+
}
18+
19+
// treesAreMirrored checks if two binary trees are mirrored.
20+
bool treesAreMirrored(BinaryTree* left, BinaryTree* right) {
21+
// Base case: If both left and right trees are non-null and have the same value,
22+
// recursively check if their subtrees are mirrored.
23+
if (left != nullptr && right != nullptr && left->Value == right->Value) {
24+
return treesAreMirrored(left->Left, right->Right) && treesAreMirrored(left->Right, right->Left);
25+
}
26+
27+
// If either left or right tree is null or their values are not equal, they are not mirrored.
28+
// Also, if both left and right trees are null, they are considered mirrored.
29+
return left == right;
30+
}
31+
32+
int main() {
33+
// Create a binary tree for testing
34+
BinaryTree* tree = new BinaryTree();
35+
tree->Value = 1;
36+
tree->Left = new BinaryTree();
37+
tree->Left->Value = 2;
38+
tree->Right = new BinaryTree();
39+
tree->Right->Value = 2;
40+
tree->Left->Left = new BinaryTree();
41+
tree->Left->Left->Value = 3;
42+
tree->Right->Right = new BinaryTree();
43+
tree->Right->Right->Value = 3;
44+
45+
// Check if the tree is symmetrical
46+
bool isSymmetrical = SymmetricalTree(tree);
47+
48+
// Output the result
49+
if (isSymmetrical) {
50+
cout << "The binary tree is symmetrical." << endl;
51+
} else {
52+
cout << "The binary tree is not symmetrical." << endl;
53+
}
54+
55+
// Clean up the allocated memory
56+
delete tree->Left->Left;
57+
delete tree->Right->Right;
58+
delete tree->Left;
59+
delete tree->Right;
60+
delete tree;
61+
62+
return 0;
63+
}

0 commit comments

Comments
 (0)