Repository navigation
Expand file tree
/
Copy pathMirrorTree.java
More file actions
86 lines (77 loc) · 1.9 KB
/
Copy pathMirrorTree.java
File metadata and controls
86 lines (77 loc) · 1.9 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
import java.io.*;
import java.util.*;
class Tree{
int data;
Tree left, right;
Tree(int key){
data = key;
left = right = null;
}
}
class MirrorTree{
public static Tree createMirror(Tree root){
if( root == null) return root;
createMirror(root.left);
createMirror(root.right);
Tree temp;
temp = root.left;
root.left = root.right;
root.right = temp;
return root;
}
public static void printTree(Tree root){
if(root == null) return;
printTree(root.left);
System.out.println(root.data);
printTree(root.right);
}
public static void levelOrder(Tree root){
Queue<Tree> que = new LinkedList<Tree>();
que.add(root);
int level = 0;
System.out.println("*********************");
while(!que.isEmpty()){
level = que.size();
while(level > 0){
Tree temp = que.poll();
System.out.print("->"+temp.data);
if(temp.left !=null)
que.add(temp.left);
if(temp.right !=null)
que.add(temp.right);
level--;
}
System.out.println();
}
}
public static void main(String arg[]){
Tree root;
root = new Tree(10);
root.left = new Tree(5);
root.right = new Tree(15);
root.left.left = new Tree(3);
root.left.right = new Tree(7);
root.right.left = new Tree(12);
root.right.right = new Tree(17);
root.left.left.left = new Tree(1);
root.left.left.right = new Tree(4);
createMirror(root);
printTree(root);
levelOrder(root);
}
}
Input:
/*
10
/ \
5 15
/ \ / \
3 7 12 17
/ \
1 4
*/
Output:
->10
->15->5
->17->12->7->3
->4->1