Skip to content

Commit cb11dbd

Browse files
author
Antesh Sharma
committed
mirror or symmetry or inverted BST
1 parent 27ca967 commit cb11dbd

File tree

1 file changed

+106
-0
lines changed

1 file changed

+106
-0
lines changed
Lines changed: 106 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,106 @@
1+
package com.antesh;
2+
3+
/* Mirror of a Tree: Mirror of a Binary Tree T is another Binary Tree M(T) with left and right children of all non-leaf nodes interchanged.
4+
* (1) Call Mirror for left-subtree i.e., Mirror(left-subtree)
5+
(2) Call Mirror for right-subtree i.e., Mirror(right-subtree)
6+
(3) Swap left and right subtrees.
7+
temp = left-subtree
8+
left-subtree = right-subtree
9+
right-subtree = temp
10+
* */
11+
12+
public class MirrorOrSymmetryOrInvertedBSTree {
13+
static Node root;
14+
15+
public static void display(Node node) {
16+
System.out.print(node.data + " ");
17+
}
18+
19+
public static Node insert(Node node, int data) {
20+
if (node == null) {
21+
return new Node(data);
22+
}
23+
24+
if (data < node.data) {
25+
node.left = insert(node.left, data);
26+
} else {
27+
node.right = insert(node.right, data);
28+
}
29+
return node;
30+
}
31+
32+
public static void mirror() {
33+
root = mirror(root);
34+
}
35+
36+
public static Node mirror(Node node) {
37+
if (node == null) {
38+
return node;
39+
}
40+
41+
Node left = mirror(node.left);
42+
Node right = mirror(node.right);
43+
44+
node.left = right;
45+
node.right = left;
46+
47+
return node;
48+
}
49+
50+
static void inorder(Node node) {
51+
if (node == null) {
52+
return;
53+
}
54+
55+
inorder(node.left);
56+
System.out.print(node.data + " ");
57+
inorder(node.right);
58+
}
59+
60+
static class Node {
61+
int data;
62+
Node left;
63+
Node right;
64+
65+
public Node(int data) {
66+
this.data = data;
67+
this.left = null;
68+
this.right = null;
69+
}
70+
}
71+
72+
public static void main(String[] args) {
73+
int[] arr = {1,2,3,4,5};
74+
for (int num: arr) {
75+
root = insert(root, num);
76+
}
77+
78+
System.out.println("In order tree: ");
79+
inorder(root);
80+
81+
mirror();
82+
83+
System.out.println("\nIn order of mirror tree: ");
84+
inorder(root);
85+
86+
System.out.println();
87+
root = null;
88+
root = new Node(1);
89+
root.left = new Node(2);
90+
root.right = new Node(3);
91+
root.left.left = new Node(4);
92+
root.left.right = new Node(5);
93+
94+
System.out.println("In order tree: ");
95+
inorder(root);
96+
97+
mirror();
98+
99+
System.out.println("\nIn order of mirror tree: ");
100+
inorder(root);
101+
}
102+
}
103+
104+
105+
106+

0 commit comments

Comments
 (0)