File tree Expand file tree Collapse file tree 1 file changed +87
-0
lines changed Expand file tree Collapse file tree 1 file changed +87
-0
lines changed Original file line number Diff line number Diff line change
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
+ }
You can’t perform that action at this time.
0 commit comments