-
Notifications
You must be signed in to change notification settings - Fork 43
/
Mirror of a Binary Tree.java
73 lines (54 loc) · 1.32 KB
/
Mirror of a Binary Tree.java
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
//Mirror of a Binary Tree
public class Main {
static class node
{
int value;
node left;
node right;
}
static node createNode(int value)
{
node newNode=new node();
newNode.value=value;
newNode.left= null;
newNode.right=null;
return newNode;
}
static void inorder(node root)
{
if(root==null)
{
return;
}
//left root right
inorder(root.left);
System.out.print(" "+root.value);
inorder(root.right);
}
static node mirrorify(node root)
{
if(root==null)
{
return null;
}
//create new mirror node from original tree node
node mirrorNode=createNode(root.value);
mirrorNode.right=mirrorify(root.left);
mirrorNode.left=mirrorify(root.right);
return mirrorNode;
}
public static void main(String[] args) {
node tree=createNode(1);
tree.right=createNode(3);
tree.left=createNode(2);
tree.left.left=createNode(4);
tree.left.right=createNode(5);
//Inorder of Original Tree
System.out.print("Inorder of Original Tree:");
inorder(tree);
node mirror=null;
mirror=mirrorify(tree);
System.out.print("\nMirror of Original Tree:");
inorder(mirror);
}
}