-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTrees.java
More file actions
1635 lines (1303 loc) · 47.3 KB
/
Trees.java
File metadata and controls
1635 lines (1303 loc) · 47.3 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
import java.io.IOException;
import java.util.Collections;
import java.util.LinkedList;
import java.util.Scanner;
import java.util.ArrayList;
import java.util.List;
import java.util.HashMap;
class Trees {
public class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode() {
}
TreeNode(int val) {
this.val = val;
}
TreeNode(int val, TreeNode left, TreeNode right) {
this.val = val;
this.left = left;
this.right = right;
}
}
class Node {
int data;
Node left, right;
Node(int item) {
data = item;
left = right = null;
}
}
// 144. Binary Tree Preorder Traversal (Morris Traversal)
/*
* Morris Traversal : O(3n), O(1)
Each node is visited 3 times max.
When the root is visited 1st time, make the connection with rightmost child of its
left child, and add root to ans.
When root is visited 2nd time, break the connection and move to right child.
*/
public List<Integer> preorderTraversal(TreeNode root) {
List<Integer> ans = new ArrayList<>();
while (root != null) {
if (root.left == null) {
ans.add(root.val);
root = root.right;
} else {
TreeNode rootp1 = root.left;
while (rootp1.right != null && rootp1.right != root) {
rootp1 = rootp1.right;
}
if (rootp1.right == null) { // 1st time -> make connection, add to ans
ans.add(root.val);
rootp1.right = root;
root = root.left;
} else { // 2nd time -> break connection
rootp1.right = null;
root = root.right;
}
}
}
return ans;
}
// 94. Binary Tree Inorder Traversal (Morris Traversal)
/*
* Morris Traversal : O(3n), O(1) Each node is visited 3 times max. When the
* root is visited 1st time, make the connection with rightmost child of its
* left child. When root is visited 2nd time, break the connection, , add root
* to ans and move to right child.
*/
public List<Integer> inorderTraversal(TreeNode root) {
List<Integer> ans = new ArrayList<>();
while (root != null) {
if (root.left == null) {
ans.add(root.val);
root = root.right;
} else {
TreeNode rootp1 = root.left;
while (rootp1.right != null && rootp1.right != root) {
rootp1 = rootp1.right;
}
if (rootp1.right == null) { // 1st time
rootp1.right = root;
root = root.left;
} else { // 2nd time -> break connection, add to ans
ans.add(root.val);
rootp1.right = null;
root = root.right;
}
}
}
return ans;
}
// 145. Binary Tree Postorder Traversal
/*
* Morris Traversal does not exist for postorder, but you can use a jugaad. //
* If we write a reverse Preorder, then reverse it, that gives us postorder. //
* To get reverse Preorder, we just reverse the left right calls. // So instead
* of Root Left Right , we do Root Right Left //So use this and then reverse the
* traversal
*
* But this will require extra space to store and reverse the reverse preorder.k
* So, it is not exactly morris traversal. But if you have to do it then this is
* the way to do it.
*/
public List<Integer> postorderTraversal(TreeNode root) {
List<Integer> ans = new ArrayList<>();
// write exact same as preorder, and
// make all left-> right, and right -> left
while (root != null) {
if (root.right == null) {
ans.add(root.val);
root = root.left;
} else {
TreeNode rootp1 = root.right;
while (rootp1.left != null && rootp1.left != root) {
rootp1 = rootp1.left;
}
if (rootp1.left == null) { // 1st time -> make connection, add to ans
ans.add(root.val);
rootp1.left = root;
root = root.right;
} else { // 2nd time -> break connection
rootp1.left = null;
root = root.left;
}
}
}
Collections.reverse(ans);
return ans;
}
// 199. Binary Tree Right Side View
public List<Integer> rightSideView(TreeNode root) {
if (root == null)
return new ArrayList<>();
TreeNode node = root;
List<Integer> ans = new ArrayList<>();
LinkedList<TreeNode> que = new LinkedList<>();
que.add(node);
while (que.size() > 0) {
int size = que.size();
boolean firstNode = true;
while (size-- > 0) {
TreeNode rnode = que.poll();
// add first node of each reverse level into ans
if (firstNode) {
ans.add(rnode.val);
firstNode = false;
}
// add right node first -> to get the level in reverse
if (rnode.right != null)
que.add(rnode.right);
// add left node
if (rnode.left != null)
que.add(rnode.left);
}
}
return ans;
}
// Left View of Binary Tree (GFG)
ArrayList<Integer> leftView(Node root) {
if (root == null)
return new ArrayList<>();
Node node = root;
ArrayList<Integer> ans = new ArrayList<>();
LinkedList<Node> que = new LinkedList<>();
que.add(node);
while (que.size() > 0) {
int size = que.size();
boolean firstNode = true;
while (size-- > 0) {
Node rnode = que.poll();
// add first node of each level into ans
if (firstNode) {
ans.add(rnode.data);
firstNode = false;
}
// add left node
if (rnode.left != null)
que.add(rnode.left);
// add right node
if (rnode.right != null)
que.add(rnode.right);
}
}
return ans;
}
// Top View of Binary Tree
// (https://practice.geeksforgeeks.org/problems/top-view-of-binary-tree/1)
/*
Eg: leftWidth = -2, Then in the array, its index is 0, so to map the range
leftWidth to rightWidth to the array of size (rightWidth - leftWidth + 1)
We do -leftWidth from all level values
So, if the width was -2 to 5, and array size would have been 5 - (-2) + 1 = 8
And then the level -1 would be mapped to -1 - (-2) = 1 which is correct
Similarly
-2 gets mapped to 0
-1 to 1
0 to 2
1 to 3 ..... so on till 5 gets mapped to 7 which is last index
*/
static class pair {
Node node;
int vl;
pair(Node node, int vl) {
this.node = node;
this.vl = vl;
}
}
// Approach 1:
static int rightwidth = Integer.MIN_VALUE;
static int leftwidth = Integer.MAX_VALUE;
static int leftMinValue = 0;
static int rightMaxValue = 0;
static void width(Node node, int lev) {
if (node == null)
return;
leftwidth = Math.min(leftwidth, lev);
rightwidth = Math.max(rightwidth, lev);
width(node.left, lev - 1);
width(node.right, lev + 1);
}
static ArrayList<Integer> topView(Node node) {
// add your code
if (node == null)
return new ArrayList<>();
width(node, 0);
int[] ans = new int[rightwidth - leftwidth + 1];
Arrays.fill(ans, -1);
LinkedList<pair> que = new LinkedList<>();
que.addLast(new pair(node, -leftwidth));
while (que.size() != 0) {
int size = que.size();
while (size-- > 0) {
pair rpair = que.removeFirst();
if (ans[rpair.vl] == -1)
ans[rpair.vl] = rpair.node.data;
if (rpair.node.left != null)
que.addLast(new pair(rpair.node.left, rpair.vl - 1));
if (rpair.node.right != null)
que.addLast(new pair(rpair.node.right, rpair.vl + 1));
}
}
ArrayList<Integer> temp = new ArrayList<>();
for (int ele : ans)
if (ele != -1)
temp.add(ele);
return temp;
}
// Approach 2: without finding the width -> use a hashmap instead of array to store the vertical level
static ArrayList<Integer> topView(Node node) {
// add your code
if (node == null)
return new ArrayList<>();
HashMap<Integer, Integer> map = new HashMap<>();
LinkedList<pair> que = new LinkedList<>();
que.addLast(new pair(node, 0));
int min = 0; // leftMin
int max = 0; // rightMax
while (que.size() != 0) {
int size = que.size();
while (size-- > 0) {
pair rpair = que.removeFirst();
// update the leftMin, rightMax
min = Math.min(min, rpair.vl);
max = Math.max(max, rpair.vl);
// add only the first value of each vertical level in map
if (map.containsKey(rpair.vl) == false) {
map.put(rpair.vl, rpair.node.data);
}
if (rpair.node.left != null)
que.addLast(new pair(rpair.node.left, rpair.vl - 1));
if (rpair.node.right != null)
que.addLast(new pair(rpair.node.right, rpair.vl + 1));
}
}
// add the top view nodes in answer
ArrayList<Integer> ans = new ArrayList<>();
for (int i = min; i <= max; i++) {
ans.add(map.get(i));
}
return ans;
}
// Bottom View of Binary Tree
// (https://practice.geeksforgeeks.org/problems/bottom-view-of-binary-tree/1)
static class pair {
Node node;
int vl;
pair(Node node, int vl) {
this.node = node;
this.vl = vl;
}
}
// Approach 1:
static int rightwidth = Integer.MIN_VALUE;
static int leftwidth = Integer.MAX_VALUE;
static int leftMinValue = 0;
static int rightMaxValue = 0;
static void width(Node node, int lev) {
if (node == null)
return;
leftwidth = Math.min(leftwidth, lev);
rightwidth = Math.max(rightwidth, lev);
width(node.left, lev - 1);
width(node.right, lev + 1);
}
public ArrayList<Integer> bottomView(Node root) {
// Code here
Node node = root;
if (node == null)
return new ArrayList<>();
width(node, 0);
int[] ans = new int[rightwidth - leftwidth + 1];
LinkedList<pair> que = new LinkedList<>();
que.addLast(new pair(node, -leftwidth));
while (que.size() != 0) {
int size = que.size();
while (size-- > 0) {
pair rpair = que.removeFirst();
ans[rpair.vl] = rpair.node.data;
if (rpair.node.left != null)
que.addLast(new pair(rpair.node.left, rpair.vl - 1));
if (rpair.node.right != null)
que.addLast(new pair(rpair.node.right, rpair.vl + 1));
}
}
ArrayList<Integer> temp = new ArrayList<>();
for (int ele : ans)
if (ele != 0)
temp.add(ele);
return temp;
}
// Approach 2: without finding width -> use hashmap instead of array
public ArrayList<Integer> bottomView(Node node) {
// add your code
if (node == null)
return new ArrayList<>();
HashMap<Integer, Integer> map = new HashMap<>();
LinkedList<pair> que = new LinkedList<>();
que.addLast(new pair(node, 0));
int min = 0; // leftMin
int max = 0; // rightMax
while (que.size() != 0) {
int size = que.size();
while (size-- > 0) {
pair rpair = que.removeFirst();
// update the leftMin, rightMax
min = Math.min(min, rpair.vl);
max = Math.max(max, rpair.vl);
// update the node for the vertical level in hashmap
map.put(rpair.vl, rpair.node.data);
if (rpair.node.left != null)
que.addLast(new pair(rpair.node.left, rpair.vl - 1));
if (rpair.node.right != null)
que.addLast(new pair(rpair.node.right, rpair.vl + 1));
}
}
// add the bottom view nodes in answer
ArrayList<Integer> ans = new ArrayList<>();
for (int i = min; i <= max; i++) {
ans.add(map.get(i));
}
return ans;
}
// 987. Vertical Order Traversal of a Binary Tree
public class Pair implements Comparable<Pair> {
public TreeNode node;
public int level; // stores vertical level
public Pair(TreeNode n, int lvl) {
this.node = n;
this.level = lvl;
}
@Override
public int compareTo(Pair o) {
// if horizontal level is different -> sort according to horizontal level
if (this.level != o.level)
return this.level - o.level;
// if same horiontal level -> sort according to node values
else
return this.node.val - o.node.val;
}
}
public List<List<Integer>> verticalTraversal(TreeNode root) {
TreeNode node = root;
LinkedList<Pair> que = new LinkedList<>();
HashMap<Integer, ArrayList<Pair>> map = new HashMap<>();
int min = Integer.MAX_VALUE;
int max = Integer.MIN_VALUE;
que.addFirst(new Pair(node, 0));
int hl = 0;
while (que.size() > 0) {
int size = que.size();
while (size-- > 0) {
Pair rpair = que.removeFirst();
min = Math.min(min, rpair.level);
max = Math.max(max, rpair.level);
if (!map.containsKey(rpair.level)) {
map.put(rpair.level, new ArrayList<Pair>());
}
map.get(rpair.level).add(new Pair(rpair.node, hl));
if (rpair.node.left != null)
que.addLast(new Pair(rpair.node.left, rpair.level - 1));
if (rpair.node.right != null)
que.addLast(new Pair(rpair.node.right, rpair.level + 1));
}
hl++;
}
List<List<Integer>> ans = new ArrayList<>();
for (int i = min; i <= max; i++) {
ArrayList<Pair> nodes = map.get(i);
// Sort the vertical level such that nodes on same horizontal level are sorted
// in increasing order
Collections.sort(nodes);
List<Integer> lvl = new ArrayList<>();
for (Pair pr : nodes) {
lvl.add(pr.node.val);
}
ans.add(lvl);
}
return ans;
}
// Diagonal Traversal of Binary Tree
// (https://practice.geeksforgeeks.org/problems/diagonal-traversal-of-binary-tree/1)
/*
* On GFG, the diagonal order is taken in DFS form, not levelOrder. So, BFS
* gives the correct elements in a diagonal but in wrong order.
*
* The DFS Solution passes in C++. But in java gets a TLE
*/
// Approach 1: BFS
public ArrayList<Integer> diagonal(TreeNode root) {
TreeNode node = root;
LinkedList<Pair> que = new LinkedList<>();
HashMap<Integer, ArrayList<Integer>> map = new HashMap<>();
int min = Integer.MAX_VALUE;
int max = Integer.MIN_VALUE;
que.addFirst(new Pair(node, 0));
while (que.size() > 0) {
int size = que.size();
while (size-- > 0) {
Pair rpair = que.removeFirst();
min = Math.min(min, rpair.level);
max = Math.max(max, rpair.level);
if (!map.containsKey(rpair.level)) {
map.put(rpair.level, new ArrayList<Integer>());
}
map.get(rpair.level).add(rpair.node.val);
if (rpair.node.left != null)
que.addLast(new Pair(rpair.node.left, rpair.level - 1));
if (rpair.node.right != null)
que.addLast(new Pair(rpair.node.right, rpair.level + 0));
}
}
ArrayList<Integer> ans = new ArrayList<>();
for (int i = min; i <= max; i++) {
ArrayList<Integer> nodes = map.get(i);
for (int j = 0; j < nodes.size(); j++) {
ans.add(nodes.get(j));
}
}
return ans;
}
// Approach 2: DFS
public int leftMin = Integer.MAX_VALUE;
public int rightMax = Integer.MIN_VALUE;
public void diagonal(Node node, int lvl, HashMap<Integer, ArrayList<Integer>> map) {
if (node == null)
return;
if (!map.containsKey(lvl))
map.put(lvl, new ArrayList<Integer>());
map.get(lvl).add(node.data);
leftMin = Math.min(leftMin, lvl);
rightMax = Math.max(rightMax, lvl);
diagonal(node.left, lvl - 1, map);
diagonal(node.right, lvl + 0, map);
}
public ArrayList<Integer> diagonal(Node root) {
// add your code here.
HashMap<Integer, ArrayList<Integer>> map = new HashMap<>();
diagonal(root, 0, map);
ArrayList<Integer> ans = new ArrayList<>();
for (int i = rightMax; i >= leftMin; i--) {
ArrayList<Integer> nodes = map.get(i);
for (int j = 0; j < nodes.size(); j++) {
ans.add(nodes.get(j));
}
}
return ans;
}
// 878 · Boundary of Binary Tree
/*
Approach:
1. Add the left boundary to res, and save the lefmost node
2. Add the leaf nodes of the left subtree of root, but dont add the leftmost node again
3. Add the leaf nodes of the right subtree of root
4. Add the right boundary, but dont add the rightmost node, as it would have already
been added by the leaf nodes of right subtree
*/
public TreeNode leftMostNode = null;
public TreeNode rightMostNode = null;
public void leftBoundary(TreeNode node, List<Integer> res) {
if (node == null)
return;
res.add(node.val);
if (node.left != null)
leftBoundary(node.left, res);
else if (node.right != null)
leftBoundary(node.right, res);
else
leftMostNode = node;
}
public void rightBoundary(TreeNode node, List<Integer> res) {
if (node == null)
return;
if (node.right != null)
rightBoundary(node.right, res);
else if (node.left != null)
rightBoundary(node.left, res);
else
rightMostNode = node;
if (node != rightMostNode)
res.add(node.val);
}
public void leafNodes(TreeNode node, List<Integer> res) {
if (node == null)
return;
if (node.left == null && node.right == null) {
if (node != leftMostNode)
res.add(node.val);
return;
}
if (node.left != null)
leafNodes(node.left, res);
if (node.right != null)
leafNodes(node.right, res);
}
public List<Integer> boundaryOfBinaryTree(TreeNode root) {
// write your code here
if (root == null)
return new ArrayList<>();
List<Integer> res = new ArrayList<>();
res.add(root.val);
leftBoundary(root.left, res);
leafNodes(root.left, res);
leafNodes(root.right, res);
rightBoundary(root.right, res);
return res;
}
// 1145. Binary Tree Coloring Game
/*
Approach:
To win you have to choose a one of 3 nodes: parent of x, left child of x, right of x
You can only win if 1 of following conditions is true:
1. Count of nodes in left subtree of x node > totalNodes/2
2. Count of nodes in right subtree of x node > totalNodes/2
3. Count of nodes in rest of the tree i.e. n - leftCount - rightCount - 1(for node x) > totalNodes/2
*/
public boolean res = false;
public int countNodes(TreeNode node, int n, int x) {
if (node == null)
return 0;
int leftCount = countNodes(node.left, n, x);
int rightCount = countNodes(node.right, n, x);
if (node.val == x) {
if (leftCount > n / 2 || rightCount > n / 2 || n - (leftCount + rightCount + 1) > n / 2)
res = true;
}
return leftCount + rightCount + 1;
}
public boolean btreeGameWinningMove(TreeNode root, int n, int x) {
res = false;
countNodes(root, n, x);
return res;
}
// 222. Count Complete Tree Nodes
/*
Explanation in c++ code
*/
public int getLeftHeight(TreeNode root) {
int count = 1;
while (root.left != null) {
root = root.left;
count++;
}
return count;
}
public int getRightHeight(TreeNode root) {
int count = 1;
while (root.right != null) {
root = root.right;
count++;
}
return count;
}
public int countNodes(TreeNode root) {
if (root == null)
return 0;
int lh = getLeftHeight(root);
int rh = getRightHeight(root);
if (lh == rh)
return (1 << lh) - 1;
return countNodes(root.left) + countNodes(root.right) + 1;
}
// 105. Construct Binary Tree from Preorder and Inorder Traversal
public TreeNode preAndIn(int[] pre, int psi, int pei, int[] in, int isi, int iei, HashMap<Integer, Integer> map) {
if (psi > pei || isi > iei)
return null;
TreeNode root = new TreeNode(pre[psi]);
int idx = map.get(pre[psi]);
int tot = idx - isi;
root.left = preAndIn(pre, psi + 1, psi + tot, in, isi, idx - 1, map);
root.right = preAndIn(pre, psi + tot + 1, pei, in, idx + 1, iei, map);
return root;
}
public TreeNode buildTree(int[] preorder, int[] inorder) {
HashMap<Integer, Integer> map = new HashMap<>();
for (int i = 0; i < inorder.length; i++) {
map.put(inorder[i], i);
}
return preAndIn(preorder, 0, preorder.length - 1, inorder, 0, inorder.length - 1, map);
}
// 106. Construct Binary Tree from Inorder and Postorder Traversal
public static TreeNode postAndIn(int[] post, int psi, int pei, int[] in, int isi, int iei,
HashMap<Integer, Integer> map) {
if (psi > pei || isi > iei)
return null;
TreeNode root = new TreeNode(post[pei]);
int idx = map.get(post[pei]);
int tot = idx - isi;
root.left = postAndIn(post, psi, psi + tot - 1, in, isi, idx - 1, map);
root.right = postAndIn(post, psi + tot, pei - 1, in, idx + 1, iei, map);
return root;
}
public TreeNode buildTree(int[] inorder, int[] postorder) {
HashMap<Integer, Integer> map = new HashMap<>();
for (int i = 0; i < inorder.length; i++) {
map.put(inorder[i], i);
}
return postAndIn(postorder, 0, postorder.length - 1, inorder, 0, inorder.length - 1, map);
}
// 98. Validate Binary Search Tree
// Approach 1: Inorder
/*
* Traverse in inorder. If prev node value >= current node value, then ans is
* false
*/
public TreeNode prev = null;
public boolean isValidBST(TreeNode root) {
if (root == null)
return true;
boolean res = true;
res = res && isValidBST(root.left);
if (prev != null && prev.val >= root.val) {
return false;
}
prev = root;
res = res && isValidBST(root.right);
return res;
}
// Approach 2: Preorder
/*
* Do Preorder traversal. For each node check if it is in the range (lo, hi) For
* root range is (-inf, inf) For left node range becomes (-inf, curr.val) For
* right node range becomes (curr.val, inf)
*/
public boolean isValidBST(TreeNode root, long lo, long hi) {
if (root == null)
return true;
if (root.val <= lo || root.val >= hi)
return false;
return isValidBST(root.left, lo, root.val) && isValidBST(root.right, root.val, hi);
}
public boolean isValidBST(TreeNode root) {
return isValidBST(root, Long.MIN_VALUE, Long.MAX_VALUE);
}
// Construct BST from Postorder (GFG)
// Approach 1: Using Next Smaller Element (Not Submitted)
public Node constructTree(int[] post, int[] nextSmaller, int psi, int pei) {
if (psi > pei)
return null;
Node root = new Node(post[pei]);
root.left = constructTree(post, nextSmaller, psi, nextSmaller[pei]);
root.right = constructTree(post, nextSmaller, nextSmaller[pei] + 1, pei - 1);
return root;
}
public static Node constructTree(int post[], int n) {
// Find the Next Smaller Element in left for postorder elements
LinkedList<Integer> st = new LinkedList<>();
int[] nextSmaller = new int[n];
st.addLast(n - 1);
nextSmaller[0] = -1;
for (int i = n - 1; i > 0; i--) {
while (st.getLast() != -1 && post[st.getLast()] > post[i]) {
nextSmaller[i] = st.removeLast();
}
st.addLast(i);
}
return constructTree(post, nextSmaller, 0, n - 1);
}
// Approach 2: (Better) Using (lower bound, upper bound)
public static int idx = -1;
public static Node constructTree(int post[], int lb, int ub) {
if (idx < 0)
return null;
if (post[idx] >= ub || post[idx] <= lb)
return null;
Node root = new Node(post[idx--]);
// Call for right child first because it is postorder array
// so right child appears first
root.right = constructTree(post, root.data, ub);
root.left = constructTree(post, lb, root.data);
return root;
}
public static Node constructTree(int post[], int n) {
idx = n - 1;
return constructTree(post, Integer.MIN_VALUE, Integer.MAX_VALUE);
}
// 1008. Construct Binary Search Tree from Preorder Traversal
// Approach: Using (lower bound, upper bound)
public static int idx = -1;
public static TreeNode constructTree(int pre[], int lb, int ub) {
if (idx == pre.length)
return null;
if (pre[idx] >= ub || pre[idx] <= lb)
return null;
TreeNode root = new TreeNode(pre[idx++]);
root.left = constructTree(pre, lb, root.val);
root.right = constructTree(pre, root.val, ub);
return root;
}
public TreeNode bstFromPreorder(int[] preorder) {
idx = 0;
return constructTree(preorder, Integer.MIN_VALUE, Integer.MAX_VALUE);
}
// Construct tree from Inorder and LevelOrder (GFG)
public Node levelAndIn(int in[], ArrayList<Integer> level, HashMap<Integer, Integer> map, int isi, int iei) {
if (isi > iei)
return null;
//Root is the first element of current level
Node root = new Node(level.get(0));
int rootIdx = map.get(level.get(0));
//get the left, right level elements from inorder
ArrayList<Integer> leftLevel = new ArrayList<>();
ArrayList<Integer> rightLevel = new ArrayList<>();
for (int i = 1; i < level.size(); i++) {
int ele = level.get(i);
if (map.get(ele) < rootIdx)
leftLevel.add(ele);
else if (map.get(ele) > rootIdx)
rightLevel.add(ele);
}
//make call for left and right child
root.left = levelAndIn(in, leftLevel, map, isi, rootIdx - 1);
root.right = levelAndIn(in, rightLevel, map, rootIdx + 1, iei);
return root;
}
Node buildTree(int inord[], int level[]) {
// your code here
HashMap<Integer, Integer> map = new HashMap<>();
ArrayList<Integer> levelOrder = new ArrayList<>();
for (int ele : level)
levelOrder.add(ele);
for (int i = 0; i < inord.length; i++)
map.put(inord[i], i);
return levelAndIn(inord, levelOrder, map, 0, inord.length - 1);
}
// 889. Construct Binary Tree from Preorder and Postorder Traversal
public TreeNode preAndPost(int[] pre, int psi, int pei, int[] post, int ppsi, int ppei) {
if (psi > pei)
return null;
if (psi == pei)
return new TreeNode(pre[psi]);
TreeNode root = new TreeNode(pre[psi]);
int idx = ppsi;
while (post[idx] != pre[psi + 1]) {
idx++;
}
int tot = idx - ppsi + 1;
root.left = preAndPost(pre, psi + 1, psi + tot, post, ppsi, idx);
root.right = preAndPost(pre, psi + tot + 1, pei, post, idx + 1, ppei - 1);
return root;
}
public TreeNode constructFromPrePost(int[] pre, int[] post) {
return preAndPost(pre,0,pre.length-1,post,0,post.length-1);
}
// 834. Sum of Distances in Tree
/*
Approach: O(n)
We use 3 steps:
1.Calculate the count node for every node's subtree