forked from anitaa1990/Android-Cheat-sheet
-
Notifications
You must be signed in to change notification settings - Fork 0
/
MirrorBinaryTreeNodes.java
123 lines (96 loc) · 3.01 KB
/
MirrorBinaryTreeNodes.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
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
package trees;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.List;
import java.util.Queue;
public class MirrorBinaryTreeNodes {
/*
* Given the root node of a binary tree, swap the 'left' and 'right' children for each node.
*
* Runtime Complexity:
* Linear, O(n)
* Every sub-tree needs to be mirrored so we visit every node once and mirror the sub-tree starting there.
* Hence run time complexity is O(n).
*
* Memory Complexity:
* Linear, O(n) in the worst case.
*
* Do a post order traversal of the binary tree.
* For every node, swap it's left child with right child.
*
* */
private static class Node {
private int data;
private Node left, right;
Node(int item) {
data = item;
left = right = null;
}
public int getData() {
return data;
}
public Node getLeft() {
return left;
}
public Node getRight() {
return right;
}
}
private Node root1;
protected void mirrorBinaryTree(Node root) {
if (root == null) {
return;
}
if (root.left != null) {
mirrorBinaryTree(root.left);
}
if (root.right != null) {
mirrorBinaryTree(root.right);
}
Node temp = root.left;
root.left = root.right;
root.right = temp;
}
protected static void levelOrderTraversal(Node root) {
if (root == null) {
return;
}
List<Queue<Node>> queues = new ArrayList<>();
queues.add(new ArrayDeque<>());
queues.add(new ArrayDeque<>());
Queue<Node> currentQueue = queues.get(0);
Queue<Node> nextQueue = queues.get(1);
currentQueue.add(root);
int levelNumber = 0;
while (!currentQueue.isEmpty()) {
Node temp = currentQueue.poll();
System.out.print(temp.data + ",");
if (temp.left != null) {
nextQueue.add(temp.left);
}
if (temp.right != null) {
nextQueue.add(temp.right);
}
if (currentQueue.isEmpty()) {
System.out.println();
++levelNumber;
currentQueue = queues.get(levelNumber % 2);
nextQueue = queues.get((levelNumber + 1) % 2);
}
}
System.out.println();
}
public static void main(String[] argv) {
MirrorBinaryTreeNodes tree = new MirrorBinaryTreeNodes();
tree.root1 = new Node(1);
tree.root1.left = new Node(2);
tree.root1.right = new Node(3);
tree.root1.left.left = new Node(4);
tree.root1.left.right = new Node(5);
tree.root1.right.left = new Node(6);
tree.root1.right.right = new Node(7);
tree.levelOrderTraversal(tree.root1);
tree.mirrorBinaryTree(tree.root1);
tree.levelOrderTraversal(tree.root1);
}
}