-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathflip_bt.cpp
More file actions
96 lines (80 loc) · 2.29 KB
/
Copy pathflip_bt.cpp
File metadata and controls
96 lines (80 loc) · 2.29 KB
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
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
#include <iostream>
#include <vector>
#include <set>
#include <queue>
#include <map>
using namespace std;
// Node structure for the binary tree
struct Node {
int data;
Node* left;
Node* right;
// Constructor to initialize
// the node with a value
Node(int val) : data(val), left(nullptr), right(nullptr) {}
};
class Solution {
private:
// Function to check if
// two subtrees are symmetric
bool isSymmetricUtil(Node* root1, Node* root2) {
// Check if either subtree is NULL
if (root1 == NULL || root2 == NULL) {
// If one subtree is NULL, the other
// must also be NULL for symmetry
return root1 == root2;
}
// Check if the data in the current nodes is equal
// and recursively check for symmetry in subtrees
return (root1->data == root2->data)
&& isSymmetricUtil(root1->left, root2->right)
&& isSymmetricUtil(root1->right, root2->left);
}
public:
// Public function to check if the
// entire binary tree is symmetric
bool isSymmetric(Node* root) {
// Check if the tree is empty
if (!root) {
// An empty tree is
// considered symmetric
return true;
}
// Call the utility function
// to check symmetry of subtrees
return isSymmetricUtil(root->left, root->right);
}
};
// Function to print the Inorder
// Traversal of the Binary Tree
void printInorder(Node* root){
if(!root){
return;
}
printInorder(root->left);
cout << root->data << " ";
printInorder(root->right);
}
int main() {
// Creating a sample binary tree
Node* root = new Node(1);
root->left = new Node(2);
root->right = new Node(2);
root->left->left = new Node(3);
root->right->right = new Node(3);
root->left->right = new Node(4);
root->right->left = new Node(4);
Solution solution;
cout << "Binary Tree (Inorder): ";
printInorder(root);
cout << endl;
bool res;
res = solution.isSymmetric(root);
if(res){
cout << "This Tree is Symmetrical" << endl;
}
else{
cout << "This Tree is NOT Symmetrical" << endl;
}
return 0;
}