-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBinaryTreeBasics.java
More file actions
1458 lines (1113 loc) · 48.7 KB
/
BinaryTreeBasics.java
File metadata and controls
1458 lines (1113 loc) · 48.7 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
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package DataStructures;
import java.util.*;
/**
<pre>
1. build tree using array
2. print tree in the form of array
3. invert tree (update, swap left and right nodes)
4. traverse using recursion
5. DFS traversals (pre-order, in-order, post-order dfs() traversals & stack traversals) ---> O(h) Space Complexity, where h is height of tree - for recursion stack space
6. BFS traversals (level order traversal using queue & stack) ---> O(w) Space Complexity, where w is width of tree
7. Morris Traversals (pre-order, in-order, post-order O(1) dfs iteration traversals) ---> O(1) Space Complexity
8. height of tree
9. diameter of tree
10. size of tree
11. clone tree via pre-order traversal
12. check if two trees are identical or not
13. check if two trees are symmetric/mirror or not
14. check if tree height is balanced or not
15. check if tree is complete
16. check if tree is full
17. check if tree is subtree of another tree
18. check if tree is binary search tree BST
19. check if tree is uni-val tree
</pre>
*
* A tree is a undirected graph which satisfies the following properties:
* - Only one Root Node (Root Node has no parent or parent node is itself)
* - An Acyclic connect graph
* - N nodes & N-1 edges
* - Two vertices are connected by exactly one edge i.e exactly one path
* Example: File System Tree or directories --> /, /usr, /temp, /usr/local, /usr/local/bin
* - root node level is always 0 (HORIZONTAL LINE)
* - root node height if it does not have any child node then 0, otherwise 1 + max(height(left), height(right))
* - calculate height from bottom
* - depth and level are same. depth is opposite of height
* - level, height and depth are edges count not nodes
* PROPERTIES OF BINARY TREE
* - Maximum number of nodes in the level l is 2^l => level 0 = 2^0, level 1 = 2^1, level 2 = 2^2, level 3 = 2^3.....
* - Total maximum number(from root to current height) of nodes at given height is "2^(h+1) - 1" or "2^(l+1) - 1". Because it's the summation of all max nodes in each level
* => 2^0 + 2^1 + 2^2 + ... + 2^(h)
* => 1 + 2 + 4 + ... + 2^h
* 1 + 2 + 4 + ... + 2^n is a geometric progression with formula a(r^(n+1)-1)/(r-1) where a = 1, r = 2
* => 1(2^(h+1)-1)/(2-1)
* => ( 2^(h+1)-1 )/(2-1)
* => (2^(h+1)-1 )/1 => 2^(h+1)-1
* - Maximum number of nodes at height h is 2^(h+1)-1 🔥
* - Minimum number of nodes at height h is h+1.
* - Minimum Height h at given nodes n is log2(n+1)-1. Because n=2^(h+1)-1 => n+1 = 2^(h+1) => log2(n+1) = h+1 => h = log2(n+1)-1
* THEORY:
* - GFG Introduction to Binary Tree: <a href="https://www.geeksforgeeks.org/introduction-to-binary-tree/">Link</a> (read all next articles)
*
*
* @author Srinivas Vadige, srinivas.vadige@gmail.com
* @since 23 Sept 2024
*/
@SuppressWarnings("unused")
public class BinaryTreeBasics {
public static class TreeNode {
int val;
TreeNode left, right;
TreeNode() {}
TreeNode(int val) { this.val = val; }
TreeNode(int val, TreeNode left, TreeNode right) {
this.val = val;
this.left = left;
this.right = right;
}
}
public static void main(String[] args) {
// 1. BUILD TREE USING ARRAY
System.out.println("1. BUILD TREE USING ARRAY");
int[] nums = new int[]{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; // which is same as 1 2 3 4 5 6 7 8 9 10 null null null null null
TreeNode root = buildTree(nums);
// 2. PRINT TREE
System.out.println("2. PRINT TREE");
printTree(root).forEach(System.out::println);
/*
1
/ \
2 3
/ \ / \
4 5 6 7
/ \ /
8 9 10
1 2 3 4 5 6 7 8 9 10 null null null null null
*/
// 3. INVERT TREE
System.out.println("\n\n3. INVERT TREE");
invertTree(root);
printTree(root).forEach(System.out::println);
/*
1
_______|_______
/ \
3 2
/ \ / \
7 6 5 4
/\ /\ /\ /\
nl nl nl nl nl 10 9 8
1 3 2 7 6 5 4 null null null null null 10 9 8
*/
invertTree(root); // invert back to get original tree
// 4. TRAVERSE TREE USING RECURSION
System.out.println("\n4. TRAVERSE TREE USING RECURSION");
travUsingRecursion(root);
// 5. DFS TRAVERSAL
System.out.println("\n\n5. DFS TRAVERSAL");
/*
DFS TRAVERSAL is of 3 types:
1. PRE-ORDER TRAVERSAL
2. IN-ORDER TRAVERSAL
3. POST-ORDER TRAVERSAL
1
/ \
2 3
/ \ / \
4 5 6 7
/ \ /
8 9 10
treeNode = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
preOrder = [1, 2, 4, 8, 9, 5, 10, 3, 6, 7] // same as pre-order recursion
inOrder = [8, 4, 9, 2, 10, 5, 1, 6, 3, 7]
postOrder = [8, 9, 4, 10, 5, 2, 6, 7, 3, 1]
*/
System.out.println("PRE-ORDER TRAVERSAL USING RECURSION");
preOrderTraversalRecursion(root);
System.out.println("\nPRE-ORDER TRAVERSAL USING STACK");
preOrderTraversalUsingStack(root);
System.out.println("\nPRE-ORDER TRAVERSAL USING STACK LEFT SCAN APPROACH"); // 🔥
preOrderTraversalUsingStackLeftScan(root);
System.out.println("\nPRE-ORDER TRAVERSAL USING QUEUE ----> TODO: can't use queue for pre-order traversal");
preOrderTraversalUsingQueue(root);
System.out.println("\nIN-ORDER TRAVERSAL USING RECURSION");
inOrderTraversalRecursion(root);
System.out.println("\nIN-ORDER TRAVERSAL USING STACK");
inOrderTraversalUsingStack(root);
System.out.println("\nIN-ORDER TRAVERSAL USING QUEUE");
inOrderTraversalUsingQueue(root);
System.out.println("\nPOST-ORDER TRAVERSAL USING RECURSION");
postOrderTraversalRecursion(root);
System.out.println("\nPOST-ORDER TRAVERSAL USING STACK");
postOrderTraversalUsingStack(root);
System.out.println("\nPOST-ORDER TRAVERSAL USING QUEUE");
postOrderTraversalUsingQueue(root);
// 6. BFS TRAVERSAL
System.out.println("\n\n6 BFS TRAVERSAL");
System.out.println("LEVEL ORDER TRAVERSAL");
levelOrderTraversal(root);
System.out.println("\n6.1 BFS LEVEL ORDER TRAVERSAL PRINT EACH LEVEL USING NULL SEPARATOR");
levelOrderTraversalPrintLevelUsingNullSeparator(root);
System.out.println("\n6.2 BFS LEVEL ORDER TRAVERSAL PRINT EACH LEVEL USING DUMMY NODE SEPARATOR");
levelOrderTraversalPrintLevelUsingDummyNodeSeparator(root);
System.out.println("\n6.3 BFS LEVEL ORDER TRAVERSAL PRINT EACH LEVEL USING LEVEL/QUEUE SIZE FOR LOOP"); // levelSize if number of nodes at that level and level number is difference
levelOrderTraversalPrintLevelUsingLevelSizeForLoop(root);
System.out.println("\n6.4 BFS LEVEL ORDER TRAVERSAL PRINT EACH LEVEL USING QUEUE NODES COUNT FOR LOOP");
levelOrderTraversalPrintLevelUsingCountAndLevelSizeForLoop(root);
// 7. MORRIS TRAVERSALS
System.out.println("\n\n7 MORRIS TRAVERSALS");
/*
Morris is a type of DFS
Same like DFS Traversals Morris Traversals are of 3 types:
1. PRE-ORDER TRAVERSAL
2. IN-ORDER TRAVERSAL
3. POST-ORDER TRAVERSAL
check in code for explanation
*/
System.out.println("\n7.1 IN-ORDER TRAVERSAL USING MORRIS TRAVERSAL");
morrisInOrderTraversal(root);
System.out.println("\n7.2 PRE-ORDER TRAVERSAL USING MORRIS TRAVERSAL");
morrisPreOrderTraversal(root);
System.out.println("\n7.3 POST-ORDER TRAVERSAL USING MORRIS TRAVERSAL");
morrisPostOrderTraversal(root);
// 8. HEIGHT OF TREE
System.out.println("\n\n 8. HEIGHT OF A BINARY TREE");
System.out.println("\n8.1 HEIGHT / DEPTH OF TREE USING RECURSION");
System.out.println(getHeight(root));
System.out.println("\n8.2 HEIGHT / DEPTH OF TREE USING DFS STACK");
System.out.println(getHeightUsingDfsStack(root));
System.out.println("\n8.3 HEIGHT / DEPTH OF TREE USING BFS QUEUE");
System.out.println(getHeightUsingBfsQueue(root));
// 9. DIAMETER OF TREE
System.out.println("\n\n9 DIAMETER OF TREE");
System.out.println("\n9.1 DIAMETER OF TREE USING RECURSION");
System.out.println(getDiameter(root));
System.out.println("\n9.2 DIAMETER OF TREE USING DFS STACK");
System.out.println(getDiameterUsingDfsStack(root));
System.out.println("\n9.3 DIAMETER OF TREE USING BFS QUEUE");
System.out.println(getDiameterUsingBfsQueue(root));
// 10. SIZE OF THE TREE (TOTAL NUMBER OF NODES)
System.out.println("\n\n10. SIZE OF THE TREE (TOTAL NUMBER OF NODES)");
System.out.println(getSize(root));
// 11. CLONE TREE VIA PRE-ORDER TRAVERSAL
System.out.println("\n\n11. CLONE TREE VIA PRE-ORDER TRAVERSAL");
cloneTree(root);
// 12. CHECK IF TWO TREES ARE IDENTICAL
System.out.println("\n\n12. CHECK IF TWO TREES ARE IDENTICAL");
TreeNode root1 = buildTree(new int[]{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}); // which is same as 1 2 3 4 5 6 7 8 9 10 null null null null null
TreeNode root2 = buildTree(new int[]{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}); // which is same as 1 2 3 4 5 6 7 8 9 10 null null null null null
System.out.println(isSameTree(root1, root2));
// 13. CHECK IF TWO TREES ARE SYMMETRIC
System.out.println("\n\n13. SYMMETRIC TREES");
System.out.println("\n13.1 CHECK IF TWO TREES ARE SYMMETRIC USING DFS");
TreeNode root3 = buildTree(new int[]{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}); // which is same as 1 2 3 4 5 6 7 8 9 10 null null null null null
System.out.println(isSymmetricUsingDfs(root3));
System.out.println("\n13.2 CHECK IF TWO TREES ARE SYMMETRIC USING BFS");
System.out.println(isSymmetricUsingBfs(root3));
// 14. CHECK IF TREE IS HEIGHT BALANCED
System.out.println("\n\n14. CHECK IF TREE IS HEIGHT BALANCED");
TreeNode root4 = buildTree(new int[]{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}); // which is same as 1 2 3 4 5 6 7 8 9 10 null null null null null
System.out.println(isBalanced(root4));
// 15. CHECK IF TREE IS COMPLETE
System.out.println("\n\n15. CHECK IF TREE IS COMPLETE");
TreeNode root5 = buildTree(new int[]{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}); // which is same as 1 2 3 4 5 6 7 8 9 10 null null null null null
System.out.println(isComplete(root5));
// 16. CHECK IF TREE IS FULL
System.out.println("\n\n16. CHECK IF TREE IS FULL");
TreeNode root6 = buildTree(new int[]{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}); // which is same as 1 2 3 4 5 6 7 8 9 10 null null null null null
System.out.println(isFull(root6));
// 17. CHECK IF TREE IS SUBTREE
System.out.println("\n\n17. CHECK IF TREE IS SUBTREE");
TreeNode root7 = buildTree(new int[]{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}); // which is same as 1 2 3 4 5 6 7 8 9 10 null null null null null
TreeNode root8 = buildTree(new int[]{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}); // which is same as 1 2 3 4 5 6 7 8 9 10 null null null null null
System.out.println(isSubtree(root7, root8));
// 18. CHECK IF TREE IS BINARY SEARCH TREE
System.out.println("\n\n18. CHECK IF TREE IS BINARY SEARCH TREE");
TreeNode root9 = buildTree(new int[]{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}); // which is same as 1 2 3 4 5 6 7 8 9 10 null null null null null
System.out.println(isBST(root9));
// 19. CHECK IF TREE IS UNI-VALUE TREE
System.out.println("\n\n19. CHECK IF TREE IS UNI-VALUE TREE");
TreeNode root10 = buildTree(new int[]{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}); // which is same as 1 2 3 4 5 6 7 8 9 10 null null null null null
System.out.println(isUniValTree(root10));
}
public static TreeNode buildTree(int[] nums) {
if (nums == null || nums.length == 0) {
return null;
}
TreeNode root = new TreeNode(nums[0]);
Queue<TreeNode> q = new LinkedList<>();
q.add(root);
int i = 1;
while (i < nums.length) {
TreeNode curr = q.remove();
if (i < nums.length) {
curr.left = new TreeNode(nums[i++]);
q.add(curr.left);
}
if (i < nums.length) {
curr.right = new TreeNode(nums[i++]);
q.add(curr.right);
}
}
return root;
}
public static List<List<String>> printTree(final TreeNode root) {
final int width = (int) Math.pow(2, getHeight(root)) - 1;
final List<List<String>> result = new ArrayList<>();
dfs(root, result, 0, width, 0, width);
return result;
}
private static void dfs(final TreeNode root, final List<List<String>> result, final int l, final int r, final int level, final int width) {
if(root != null) {
if(level >= result.size()) {
result.add(new ArrayList<>());
for(int i = 0; i < width; ++i)
result.get(level).add("");
}
final int mid = (l + r) / 2;
result.get(level).set(mid, String.valueOf(root.val));
dfs(root.left, result, l, mid, level + 1, width);
dfs(root.right, result, mid, r, level + 1, width);
}
}
public static TreeNode invertTree(TreeNode root) {
if (root == null) return null;
swapNodes(root);
return root;
}
public static void swapNodes(TreeNode node){
if(node == null) return;
TreeNode temp=node.left;
node.left=node.right;
node.right=temp;
swapNodes(node.left);
swapNodes(node.right);
}
private static void travUsingRecursion(final TreeNode root) {
if (root == null) return;
System.out.print(root.val + " ");
travUsingRecursion(root.left);
travUsingRecursion(root.right);
}
private static void preOrderTraversalRecursion(final TreeNode root) {
if (root == null) return;
System.out.print(root.val + " ");
preOrderTraversalRecursion(root.left);
preOrderTraversalRecursion(root.right);
}
private static void inOrderTraversalRecursion(final TreeNode root) {
if (root == null) return;
inOrderTraversalRecursion(root.left);
System.out.print(root.val + " ");
inOrderTraversalRecursion(root.right);
}
private static void postOrderTraversalRecursion(final TreeNode root) {
if (root == null) return;
postOrderTraversalRecursion(root.left);
postOrderTraversalRecursion(root.right);
System.out.print(root.val + " ");
}
private static void preOrderTraversalUsingStack(final TreeNode root) {
if (root == null) return;
Stack<TreeNode> stack = new Stack<>();
stack.push(root);
while(!stack.isEmpty()) {
TreeNode curr = stack.pop();
System.out.print(curr.val + " ");
if (curr.right != null) stack.push(curr.right);
if (curr.left != null) stack.push(curr.left);
}
}
public static void preOrderTraversalUsingStackLeftScan(TreeNode root) { // 🔥
Stack<TreeNode> stack = new Stack<>();
TreeNode trav = root;
while (trav != null || !stack.isEmpty()) {
// traverse to left most
while (trav != null) {
System.out.print(trav.val + " ");
stack.push(trav);
trav = trav.left;
}
trav = stack.pop(); // pop top one in stack
trav = trav.right; // => if trav.right == null then above while(trav!=null){} will skip and pop the parent node and trav.right and trav will continue
}
}
private static void inOrderTraversalUsingStack(final TreeNode root) {
if (root == null) return;
Stack<TreeNode> stack = new Stack<>();
TreeNode curr = root;
while(!stack.isEmpty() || curr != null) {
if (curr != null) {
stack.push(curr);
curr = curr.left;
} else {
curr = stack.pop();
System.out.print(curr.val + " ");
curr = curr.right;
}
}
}
public static void postOrderTraversalUsingStack(TreeNode root) {
if (root == null) return;
Stack<TreeNode> stack = new Stack<>();
Stack<TreeNode> helperStack = new Stack<>();
stack.push(root);
while (!stack.isEmpty()) {
TreeNode current = stack.pop();
helperStack.push(current);
if (current.left != null) {
stack.push(current.left);
}
if (current.right != null) {
stack.push(current.right);
}
}
while (!helperStack.isEmpty()) {
System.out.print(helperStack.pop().val + " ");
}
}
private static void postOrderTraversalUsingStack2(final TreeNode root) {
if (root == null) return;
Stack<TreeNode> stack = new Stack<>();
TreeNode current = root;
TreeNode prev = null;
do {
while (current != null) {
stack.push(current);
current = current.left;
}
while (current == null && !stack.isEmpty()) {
current = stack.peek();
if (current.right == null || current.right == prev) {
System.out.print(current.val + " ");
stack.pop();
prev = current;
current = null;
} else {
current = current.right;
}
}
} while (!stack.isEmpty());
}
public static void preOrderTraversalUsingQueue(TreeNode root) {
List<Integer> result = new ArrayList<>();
if (root == null) return;
Stack<Integer> stack = new Stack<>();
Queue<TreeNode> queue = new LinkedList<>();
queue.add(root); // Add the root to the queue
while (!queue.isEmpty()) { // Process nodes in modified reverse order: root → left → right
TreeNode current = queue.poll();
stack.push(current.val);
System.out.print(current.val + " ");
if (current.left != null) queue.add(current.left);
if (current.right != null) queue.add(current.right);
}
// System.out.println( "\n"+ stack);
}
public static void inOrderTraversalUsingQueue(TreeNode root) {
if (root == null) return;
Queue<TreeNode> queue = new LinkedList<>();
Stack<TreeNode> stack = new Stack<>();
TreeNode current = root;
while (current != null || !stack.isEmpty()) {
while (current != null) {
stack.push(current);
current = current.left;
}
current = stack.pop();
queue.add(current);
current = current.right;
}
while (!queue.isEmpty()) {
System.out.print(queue.poll().val + " ");
}
}
public static void postOrderTraversalUsingQueue(TreeNode root) {
List<Integer> result = new ArrayList<>();
if (root == null) return;
Stack<TreeNode> stack = new Stack<>();
Queue<TreeNode> queue = new LinkedList<>();
queue.add(root); // Add the root to the queue
while (!queue.isEmpty()) { // Process nodes in modified reverse order: root → left → right
TreeNode current = queue.poll();
stack.push(current);
// Add right child first, then left child
if (current.right != null) queue.add(current.right);
if (current.left != null) queue.add(current.left);
}
// Pop from the stack to reverse order into post-order: left → right → root
while (!stack.isEmpty()) {
System.out.print(stack.pop().val + " ");
}
}
private static void levelOrderTraversal(final TreeNode root) {
if (root == null) return;
Queue<TreeNode> queue = new LinkedList<>();
queue.add(root);
while(!queue.isEmpty()) {
TreeNode curr = queue.remove();
System.out.print(curr.val + " ");
if (curr.left != null) queue.add(curr.left);
if (curr.right != null) queue.add(curr.right);
}
}
// FOR BOTH BALANCED & UNBALANCED BINARY TREE
// LEVEL SEPARATOR AS NULL
private static void levelOrderTraversalPrintLevelUsingNullSeparator(final TreeNode root) {
Queue<TreeNode> queue = new LinkedList<>();
queue.add(root);
queue.add(null); // null marker for end of level
int level = 0;
while (!queue.isEmpty()) {
TreeNode node = queue.poll();
if (node==null) {
System.out.println("End of Level number: " + ++level);
if (queue.isEmpty()) break; // end of tree
// reached end of level, do something if needed
queue.add(null); // add null marker for next level
} else {
System.out.println("Node value: " + node.val);
if (node.left != null) queue.add(node.left);
if (node.right != null) queue.add(node.right);
}
}
}
// FOR BOTH BALANCED & UNBALANCED BINARY TREE
// LEVEL SEPARATOR AS DUMMY NODE WITH LEFT & RIGHT CHILDREN AS ROOT
private static void levelOrderTraversalPrintLevelUsingDummyNodeSeparator(final TreeNode root) {
Queue<TreeNode> queue = new LinkedList<>();
queue.add(root);
int level = 0;
queue.add(new TreeNode(++level, root, root)); // separator use LEVEL as val variable or Integer.MAX_VALUE
while (!queue.isEmpty()) {
TreeNode node = queue.poll();
if (node!=null && node.left==root) {
System.out.println("End of Level number: " + node.val);
if (queue.isEmpty()) break; // end of tree
// reached end of level, do something if needed
queue.add(new TreeNode(++level, root, root)); // add dummy node for next level
} else {
System.out.println("Node value: " + node.val);
if (node.left != null) queue.add(node.left);
if (node.right != null) queue.add(node.right);
}
}
}
// ONLY FOR BOTH BALANCED & UNBALANCED BINARY TREE
private static void levelOrderTraversalPrintLevelUsingLevelSizeForLoop(final TreeNode root) {
Queue<TreeNode> queue = new LinkedList<>();
queue.add(root);
int queueSize = queue.size(); // levelSize or queueSize if number of nodes at that level and level number is difference
int level = 0;
while (!queue.isEmpty()) {
for (int i = 0; i < queueSize; i++) {
TreeNode node = queue.poll();
System.out.println("Node value: " + node.val);
// process node as usual
if (node.left != null) queue.add(node.left);
if (node.right != null) queue.add(node.right);
}
System.out.println("End of Level number: " + ++level);
queueSize = queue.size();
}
}
// ONLY FOR BOTH BALANCED & UNBALANCED BINARY TREE
private static void levelOrderTraversalPrintLevelUsingCountAndLevelSizeForLoop(final TreeNode root) {
Queue<TreeNode> queue = new LinkedList<>();
queue.add(root);
int queueSize = queue.size();
int level = 0;
while (!queue.isEmpty()) {
int count =0;
for (int i = 0; i < queueSize; i++) {
TreeNode node = queue.poll();
System.out.println("Node value: " + node.val);
// process node as usual
if (node.left != null){
queue.add(node.left);
count++;
}
if (node.right != null){
queue.add(node.right);
count++;
}
}
System.out.println("End of Level number: " + ++level);
queueSize = count;
}
}
/**
<pre>
MORRIS TRAVERSALS:
------------------
Here, we have two pointers - 1.root (curr) & 2.predecessor (curr root's temp parent)
🔥 if (root.left==null) "no need to trav left then root=root.right"; else "CHECK PREDECESSOR LINK TYPE"
🔥 predecessor is curr root's left child or left child's rightmost leaf node
- last node in left subtree
- we need this predecessor node to make it as root's temp parent
🔥 create the temp link for the first time using "predecessorNode.right = currRoot"
🔥 LINK TYPE 1 ---> predecessor.right == null
- not linked yet
- left traversal is not done
- visiting root for the first time
- then -> link & move left
🔥 LINK TYPE 2 ---> predecessor.right == currRoot
- we already linked it before
- left traversal is done
- re-visited the same root
- then -> unlink & move right
🔥 if(root.left==null) "move right"
- this main condition can be satisfied when root is either a normal current root node or previous predecessor node as current root
- i.e., root.right can be right child node or previous iteration parent node (as per link)
NOTE: Just remember that if root.left==null or predecessor.right==root then move root=root.right.
STEP WISE EXPLANATION:
----------------------
Given:
1
/ \
2 3
/ \ \
4 5 6
/ \
7 8
1st iteration:
root: 1
predecessor: 5
link: 5.right = 1
root = root.left = 2
(1r)
/ \
2 3
/ \ \
4 (5p) 6
/ \
7 8
(1r)
/ ↑ \
2 | 3
/ \ | \
4 (5p) 6
/ \
7 8
2nd iteration:
root: 2
predecessor: 4
link: 4.right = 2
root = root.left = 4
1
/ ↑ \
(2r) | 3
/ \ | \
(4p) 5 6
/ \
7 8
1
/ ↑ \
(2r) | 3
/ ↑ \ | \
(4p) 5 6
/ \
7 8
3rd iteration:
root: 4
predecessor: N/A - as root.left == null
link: N/A
root = root.right = 2
1
/ ↑ \
2 | 3
/ ↑ \ | \
(4r) 5 6
/ \
7 8
4th iteration:
root: 2
predecessor: 4
link: already linked, so remove it
root = root.left = 5
1
/ ↑ \
(2r) | 3
/ ↑ \ | \
(4p) 5 6
/ \
7 8
1
/ ↑ \
(2r) | 3
/ \ | \
(4p) 5 6
/ \
7 8
5th iteration:
root: 5
predecessor: 7
link: 7.right = 5
root = root.left = 7
1
/ ↑ \
2 | 3
/ \ | \
4 (5r) 6
/ \
(7p) 8
1
/ ↑ \
2 | 3
/ \ | \
4 (5r) 6
/ ↑ \
(7p) 8
6th iteration:
root: 7
predecessor: N/A - as root.left == null
link: N/A
root = root.left = 5
1
/ ↑ \
2 | 3
/ \ | \
4 5 6
/ ↑ \
(7r) 8
7th iteration:
root: 5
predecessor: 7
link: already linked, so remove it
root = root.right = 1
1
/ ↑ \
2 | 3
/ \ | \
4 (5r) 6
/ ↑ \
(7p) 8
1
/ ↑ \
2 | 3
/ \ | \
4 (5r) 6
/ \
(7p) 8
8th iteration:
root: 1
predecessor: 5
link: already linked, so remove it
root = root.right = 3
(1r)
/ ↑ \
2 | 3
/ \ | \
4 (5p) 6
/ \
7 8
(1r)
/ \
2 3
/ \ \
4 (5p) 6
/ \
7 8
and so on... the loop is the same for 3, 6, 8 as "root.left" is always null for them
</pre>
*/
public static void morrisInOrderTraversal(final TreeNode root) {
if (root == null) return;
TreeNode curr = root;
while (curr != null) {
if (curr.left == null) {
System.out.print(curr.val + " ");
curr = curr.right;
} else { // CHECK PREDECESSOR LINK TYPE - linked or not linked
TreeNode predecessor = curr.left; // to make root's left last child as root's parent / predecessor
while (predecessor.right != null && predecessor.right != curr) predecessor = predecessor.right;
if (predecessor.right == null) { // not linked yet & left traversal is not done & visiting root for the first time
predecessor.right = curr; // link
curr = curr.left;
} else { // predecessor.right == curr root -> we already linked it before & left traversal is done & re-visited the same root
System.out.print(curr.val + " ");
predecessor.right = null; // unlink
curr = curr.right;
}
}
}
}
public static void morrisPreOrderTraversal(final TreeNode root) {
if (root == null) return;
TreeNode curr = root;
while (curr != null) {
if (curr.left == null) {
System.out.print(curr.val + " ");
curr = curr.right;
} else { // CHECK PREDECESSOR LINK TYPE - linked or not linked
TreeNode predecessor = curr.left; // to make root's left last child as root's parent / predecessor
while (predecessor.right != null && predecessor.right != curr) predecessor = predecessor.right;
if (predecessor.right == null) { // not linked yet & left traversal is not done & visiting root for the first time
System.out.print(curr.val + " ");
predecessor.right = curr; // link
curr = curr.left;
} else { // predecessor.right == curr root -> we already linked it before & left traversal is done & re-visited the same root
predecessor.right = null; // unlink
curr = curr.right;
}
}
}
}
// Morris PostOrder Traversal is bit hard, as you cannot print node when you visit it (postorder prints after exploring children).
public static void morrisPostOrderTraversal(TreeNode root) {
ArrayList<Integer> res = new ArrayList<>();
TreeNode current = root;
while (current != null) {
if (current.right == null) {
res.add(current.val);
current = current.left;
} else {
TreeNode predecessor = current.right;
while (predecessor.left != null
&& predecessor.left != current) {
predecessor = predecessor.left;
}
// If left child doesn't point to this node, then put in res this node and make left child point to this node
if (predecessor.left == null) {
res.add(current.val);
predecessor.left = current;
current = current.right;
}
// If the left child of inorder predecessor already points to this node
else {
predecessor.left = null;
current = current.left;
}
}
}
Collections.reverse(res);
System.out.println(res);
}
public static void morrisPostOrderTraversal2(TreeNode root) {
if (root == null) return;
TreeNode dummy = new TreeNode(0);
dummy.left = root;
TreeNode curr = dummy;
while (curr != null) {
if (curr.left == null) {
curr = curr.right;
} else {
TreeNode predecessor = curr.left;
// go to rightmost node of left subtree OR stop if link exists
while (predecessor.right != null && predecessor.right != curr) {
predecessor = predecessor.right;
}
if (predecessor.right == null) {
// create link
predecessor.right = curr;
curr = curr.left;
} else {
// link exists → remove it AND print reverse path