-
Notifications
You must be signed in to change notification settings - Fork 8
Expand file tree
/
Copy pathBinaryTreeExample.java
More file actions
439 lines (391 loc) · 13.4 KB
/
BinaryTreeExample.java
File metadata and controls
439 lines (391 loc) · 13.4 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
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
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Queue;
import java.util.Scanner;
import java.util.Stack;
import java.util.TreeMap;
import javax.management.QueryEval;
class BinaryTree<T> {
T data;
BinaryTree<T> left; // Left Child Reference
BinaryTree<T> right; // right child Reference
BinaryTree(T data) {
this.data = data;
// default left and right are null (Java)
}
}
class BinaryTreeOperations {
String msg = "root";
Scanner scanner = new Scanner(System.in);
int parent = -1;
BinaryTree<Integer> insert() {
System.out.println("Enter the Data for " + msg + " Node and Parent is " + parent + " For Exit Write -1 ");
int data = scanner.nextInt();
// Termination case
if (data == -1) {
return null;
}
// Create a Parent Node / root node
BinaryTree<Integer> node = new BinaryTree<>(data);
parent = data;
msg = "left";
node.left = insert();
msg = "right";
parent = data;
node.right = insert();
parent = data;
msg = "root";
return node; // return root node
}
void print(BinaryTree<Integer> currentNode) {
// Termination Case
if (currentNode == null) {
return;
}
String output = "";
output += currentNode.data + " => ";
if (currentNode.left != null) {
output += "Left : " + currentNode.left.data + " , ";
}
if (currentNode.right != null) {
output += "Right : " + currentNode.right.data + " , ";
}
System.out.println(output);
print(currentNode.left);
print(currentNode.right);
}
void preOrder(BinaryTree<Integer> root) {
// Termination Case
if (root == null) {
return;
}
// Parent, Left and then Right
System.out.println(root.data); // Parent Print
preOrder(root.left); // Small Problem
preOrder(root.right); // call when stack fall
}
void preOrderIterativeSolution(BinaryTree<Integer> root) {
// Step-0 If root is empty
if (root == null) {
return;
}
// Step-1 Start with a Stack and push the first node in a Stack
Stack<BinaryTree> stack = new Stack<>();
stack.push(root);
// Step-2 Keep Pop the Element till stack is not empty
// Pop and Print it.
// Put the right child first in a stack and then put the left child in a stack
// the benefit is left is on top .
// Ensure left is not null and right is not null
// Step-3 Keep Repeat
while (!stack.isEmpty()) {
BinaryTree<Integer> node = stack.pop();
System.out.println(node.data);
if (node.right != null) {
stack.push(node.right);
}
if (node.left != null) {
stack.push(node.left);
}
}
}
void inOrder(BinaryTree<Integer> root) {
// Termination Case
if (root == null) {
return;
}
// Left, Parent and then Right
inOrder(root.left); // Small Problem
System.out.println(root.data); // Parent Print
inOrder(root.right); // call when stack fall
}
void inOrderIterative(BinaryTree<Integer> root) {
// Step-1 Need Stack
Stack<BinaryTree<Integer>> stack = new Stack<>();
BinaryTree<Integer> temp = null;
temp = root;
while (temp != null || !stack.isEmpty()) {
while (temp != null) {
stack.push(temp);
temp = temp.left;
}
temp = stack.pop();
System.out.println(temp.data);
temp = temp.right;
}
}
void postOrder(BinaryTree<Integer> root) {
// Termination Case
if (root == null) {
return;
}
// Left, Right and then Parent
postOrder(root.left); // Small Problem
postOrder(root.right); // call when stack fall
System.out.println(root.data); // Parent Print
}
void printKthLevel(BinaryTree<Integer> root, int k) {
// Termination case
if (k == 0) {
System.out.println(root.data);
}
if (root == null) {
return;
}
// Small problem
printKthLevel(root.left, k - 1);
printKthLevel(root.right, k - 1);
}
void levelOrder(BinaryTree<Integer> root) {
// Root Node Goes in a Queue
// Step-1 Create a Queue
Queue<BinaryTree> queue = new LinkedList<>();
queue.add(root);
// Step-2 Traverse Queue till it is not empty
// 2.1 Queue poll and get the node and then look for Left and Right Child
// 2.2 Add them in a Queue
// and then Do Repeat the Step No -2.
while (!queue.isEmpty()) {
BinaryTree<Integer> node = queue.poll(); // First Element
System.out.print(node.data + " , ");
if (node.left != null) {
queue.add(node.left);
}
if (node.right != null) {
queue.add(node.right);
}
}
System.out.println();
}
int burningTime(BinaryTree<Integer> root, int target) {
DepthWrapper dw = new DepthWrapper(-1);
}
// DepthWrapper (Pass by Ref)
int result;
int burn(BinaryTree<Integer> root, int target, DepthWrapper depthWrapper) {
if (root == null) {
return 0;
}
if (root.data == target) {
depthWrapper.depth = 1;
return 1;
}
DepthWrapper leftDepth = new DepthWrapper(-1);
DepthWrapper rightDepth = new DepthWrapper(-1);
int leftHeight = burn(root.left, target, leftDepth);
int rightHeight = burn(root.right, target, rightDepth);
if (leftDepth.depth != -1) {
result = Math.max(result, leftDepth.depth + 1 + rightHeight);
depthWrapper.depth = leftDepth.depth + 1;
} else if (rightDepth.depth != -1) {
result = Math.max(result, rightDepth.depth + 1 + leftHeight);
depthWrapper.depth = rightDepth.depth + 1;
}
return Math.max(leftHeight, rightHeight) + 1;
}
static class DepthWrapper {
int depth;
DepthWrapper(int depth) {
this.depth = depth;
}
}
void levelOrder2(BinaryTree<Integer> root) {
// Root Node Goes in a Queue
// Step-1 Create a Queue
Queue<BinaryTree> queue = new LinkedList<>();
queue.add(root);
// Step-2 Traverse Queue till it is not empty
// 2.1 Queue poll and get the node and then look for Left and Right Child
// 2.2 Add them in a Queue
// and then Do Repeat the Step No -2.
while (!queue.isEmpty()) {
int count = queue.size();
for (int i = 0; i < count; i++) {
BinaryTree<Integer> node = queue.poll(); // First Element
System.out.print(node.data + " , ");
if (node.left != null) {
queue.add(node.left);
}
if (node.right != null) {
queue.add(node.right);
}
}
System.out.println();
}
System.out.println();
}
int height(BinaryTree<Integer> root) {
if (root == null) {
return 0;
}
int leftHeight = height(root.left);
int rightHeight = height(root.right);
return 1 + Math.max(leftHeight, rightHeight);
}
int countNodes(BinaryTree<Integer> root) {
// If No node (reach to null so treat it as 0 count)
if (root == null) {
return 0;
}
int counter = 1;
counter = counter + countNodes(root.left);
counter = counter + countNodes(root.right);
return counter;
}
// DFT
int maxLevel = 0;
void printLeftView(BinaryTree<Integer> root, int level) {
if (root == null) {
return;
}
if (maxLevel < level) {
System.out.println(root.data);
maxLevel = level;
}
printLeftView(root.left, level + 1);
printLeftView(root.right, level + 1);
}
// BFT
void printLeftView2(BinaryTree<Integer> root) {
if (root == null) {
return;
}
Queue<BinaryTree<Integer>> queue = new LinkedList<>();
queue.add(root);
while (!queue.isEmpty()) {
int count = queue.size();
for (int i = 0; i < count; i++) {
BinaryTree<Integer> node = queue.poll();
if (i == 0) {
System.out.println(node.data);
}
if (node.left != null) {
queue.add(node.left);
}
if (node.right != null) {
queue.add(node.right);
}
}
}
}
void verticalOrderHelper(BinaryTree<Integer> root,
int distance, TreeMap<Integer, ArrayList<Integer>> map) {
// Termination Case
if (root == null) {
return;
}
// Stack Build
if (map.get(distance) == null) {
// There is no such distance present in the map
// first time it is coming in map.
// Create a Fresh List
ArrayList<Integer> list = new ArrayList<>();
list.add(root.data);
map.put(distance, list); // Add Key as a Distance and Value as a List
} else {
// The key is already present in the map
ArrayList<Integer> list = map.get(distance); // Fetch the List from that key.
list.add(root.data);
map.put(distance, list);
}
// Small Problem
verticalOrderHelper(root.left, distance - 1, map);
verticalOrderHelper(root.right, distance + 1, map);
// Stack Fall
}
void verticalOrder(BinaryTree<Integer> root) {
int distance = 0; // root
TreeMap<Integer, ArrayList<Integer>> map = new TreeMap<>();
verticalOrderHelper(root, distance, map);
for (Map.Entry<Integer, ArrayList<Integer>> m : map.entrySet()) {
System.out.println(m.getKey() + " " + m.getValue());
}
}
void verticalOrderIterative(BinaryTree<Integer> root) {
Queue<NodeVerticalPair> queue = new LinkedList<>();
queue.add(new NodeVerticalPair(root, 0));
HashMap<Integer, List<Integer>> map = new HashMap<>();
int minDistance = 0;
int maxDistance = 0;
while (queue.size() != 0) {
int size = queue.size(); // PreFetch the Queue Size
while (size > 0) {
// Queue Poll the Element
NodeVerticalPair pair = queue.poll();
// Min and Max Because of Using HashMap (Not Sorted)
minDistance = Math.min(minDistance, pair.distance);
maxDistance = Math.max(maxDistance, pair.distance);
// Now Put the Node in the HashMap
map.putIfAbsent(pair.distance, new ArrayList<>());
map.get(pair.distance).add(pair.node.data);
if (pair.node.left != null) {
queue.add(new NodeVerticalPair(pair.node.left, pair.distance - 1));
}
if (pair.node.right != null) {
queue.add(new NodeVerticalPair(pair.node.right, pair.distance + 1));
}
size--;
}
}
// Print in Order/ Sorted by Key
for (int i = minDistance; i <= maxDistance; i++) {
System.out.println(i + " " + map.get(i));
}
}
void diagonalView(BinaryTree<Integer> root) {
Queue<BinaryTree<Integer>> queue = new LinkedList<>();
queue.add(root);
while (queue.size() != 0) {
int size = queue.size();
while (size > 0) {
BinaryTree<Integer> node = queue.poll();
while (node != null) {
if (node.left != null) {
queue.add(node.left);
}
System.out.print(node.data + " ");
node = node.right;
}
size--;
}
System.out.println();
}
}
boolean printAncestors(BinaryTree<Integer> root, int search) {
if (root == null) {
return false;
}
if (root.data == search) {
return true;
}
if (printAncestors(root.left, search) || printAncestors(root.right, search)) {
System.out.println(root.data);
return true;
}
return false;
}
}
public class BinaryTreeExample {
public static void main(String[] args) {
BinaryTreeOperations opr = new BinaryTreeOperations();
BinaryTree<Integer> root = opr.insert();
// opr.print(root);
// opr.levelOrder2(root);
// opr.printLeftView(root, 1);
// opr.verticalOrder(root);
// opr.verticalOrderIterative(root);
// opr.printKthLevel(root, 2);
opr.diagonalView(root);
}
}
class NodeVerticalPair {
BinaryTree<Integer> node; // Holding the Node Ref
int distance; // every node distance
NodeVerticalPair(BinaryTree<Integer> node, int distance) {
this.node = node;
this.distance = distance;
}
}