Skip to content

Commit 3d95bda

Browse files
authored
Algo for Mirror of Binary Search Tree added (#783)
Mirror of Binary Search Tree added
1 parent 72dcb82 commit 3d95bda

File tree

1 file changed

+87
-0
lines changed

1 file changed

+87
-0
lines changed
Lines changed: 87 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,87 @@
1+
package Binarytree;
2+
3+
4+
import java.util.Scanner;
5+
6+
class Node{
7+
int data;
8+
Node left;
9+
Node right;
10+
Node(int element)
11+
{
12+
this.data = element;
13+
this.left = this.right = null;
14+
}
15+
}
16+
17+
class BST_mirror{
18+
Node root;
19+
BST_mirror()
20+
{
21+
root = null;
22+
}
23+
void addNode(int element)
24+
{
25+
root = add(root,element);
26+
}
27+
Node add(Node node, int element)
28+
{
29+
if(node == null)
30+
return new Node(element);
31+
if(element<=node.data)
32+
node.left = add(node.left,element);
33+
else
34+
if(element>node.data)
35+
node.right = add(node.right,element);
36+
37+
return node;
38+
}
39+
40+
41+
void inorder(Node root)
42+
{
43+
if(root == null)
44+
return;
45+
inorder(root.left);
46+
System.out.print(root.data+" ");
47+
inorder(root.right);
48+
}
49+
Node mirror()
50+
{
51+
return mirrorify(root);
52+
}
53+
Node mirrorify(Node node)
54+
{
55+
if(node == null)
56+
return null;
57+
// now in each step we have to create a new node and replace left right elem of old root node with new node's right left
58+
Node mirror_temp = new Node(node.data);
59+
mirror_temp.left = mirrorify(node.right);
60+
mirror_temp.right = mirrorify(node.left);
61+
return mirror_temp;
62+
}
63+
}
64+
65+
public class mirror_Tree {
66+
public static void main(String[] args) {
67+
Scanner s = new Scanner(System.in);
68+
BST_mirror obj = new BST_mirror();
69+
70+
obj.addNode(9);
71+
obj.addNode(6);
72+
obj.addNode(8);
73+
obj.addNode(7);
74+
obj.addNode(13);
75+
obj.addNode(17);
76+
obj.addNode(19);
77+
System.out.println("Inorder of original Tree");
78+
obj.inorder(obj.root);
79+
80+
System.out.println();
81+
System.out.println("Inorder of original Tree");
82+
Node mirror_node;
83+
mirror_node = obj.mirror();
84+
obj.inorder(mirror_node);
85+
86+
}
87+
}

0 commit comments

Comments
 (0)