-
Notifications
You must be signed in to change notification settings - Fork 1
/
Binary Tree.txt
1843 lines (1592 loc) · 56.3 KB
/
Binary Tree.txt
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
SOLUTIONS OF THESE QUESTIONS ARE EITHER ON GFG OR ON LEETCODE.
---------------------------------------BINARY TREE-----------------------------------------
1.Level Order Traversal
private List<List<Integer>> levelArrayList(List<List<Integer>> list, TreeNode node, int level) {
if (node == null) {
return list;
}
if (list.size() == level) {
list.add(new ArrayList<>());
}
list.get(level).add(node.val);
list = levelArrayList(list, node.left, level + 1);
list = levelArrayList(list, node.right, level + 1);
return list;
}
#In Reverse Level Order Traversal just use Collections.reverse(list); and then return
->
void reverseLevelOrder(Node node)
{
Stack<Node> S = new Stack();
Queue<Node> Q = new LinkedList();
Q.add(node);
// Do something like normal level order traversal order.Following
// are the differences with normal level order traversal
// 1) Instead of printing a node, we push the node to stack
// 2) Right subtree is visited before left subtree
while (Q.isEmpty() == false)
{
/* Dequeue node and make it root */
node = Q.peek();
Q.remove();
S.push(node);
/* Enqueue right child */
if (node.right != null)
// NOTE: RIGHT CHILD IS ENQUEUED BEFORE LEFT
Q.add(node.right);
/* Enqueue left child */
if (node.left != null)
Q.add(node.left);
}
// Now pop all items from stack one by one and print them
while (S.empty() == false)
{
node = S.peek();
System.out.print(node.data + " ");
S.pop();
}
}
-----------------------------------------------------------------------------------
2. Height of a Binary Tree
public int maxDepth(TreeNode node) {
if (node == null) {
return 0; //if zero based indexing then we would have returned -1
}
int lh = maxDepth(node.left);
int rh = maxDepth(node.right);
return Math.max(lh, rh) + 1;
}
-----------------------------------------------------------------------------------
3. Min Depth of Binary tree
public int minDepth(TreeNode root) {
if(root==null){
return 0;
}
int lh=minDepth(root.left);
int rh=minDepth(root.right);
if(lh==0){ //if right skewed tree
return rh+1;
}
if(rh==0){ //if left skewed tree
return lh+1;
}
return Math.min(lh,rh)+1;
}
-----------------------------------------------------------------------------------
4. Diameter of a Binary Tree
private class DiaPair {
int h = -1;
int d = 0;
}
private DiaPair Diameter(TreeNode node) {
if (node == null) {
return new DiaPair();
}
DiaPair ldp = Diameter(node.left);
DiaPair rdp = Diameter(node.right);
DiaPair sdp = new DiaPair();
int ld = ldp.d;
int rd = rdp.d;
int sp = ldp.h + rdp.h + 2;
sdp.h = Math.max(ldp.h, rdp.h) + 1;
sdp.d = Math.max(sp, Math.max(ld, rd));
return sdp;
}
->
private int height(TreeNode node, int[] diameter) {
if (node == null) {
return 0;
}
int lh = height(node.left, diameter);
int rh = height(node.right, diameter);
diameter[0] = Math.max(diameter[0], lh + rh);
return 1 + Math.max(lh, rh);
}
-----------------------------------------------------------------------------------
5. Invert the Tree
public TreeNode invertTree(TreeNode node) {
if(node==null){
return null;
}
TreeNode l=node.left;
TreeNode r=node.right;
node.left=r;
node.right=l;
node.left=invertTree(node.left);
node.right=invertTree(node.right);
return node;
}
-----------------------------------------------------------------------------------
6. Right Side View of Binary Tree
public List<Integer> rightSideView(TreeNode root) {
List<Integer>ans=new ArrayList<>();
Queue<TreeNode> queue = new LinkedList<>();
if(root==null){
return ans;
}
TreeNode nn = root;
queue.add(nn);
queue.add(null);
while (!queue.isEmpty()) {
TreeNode rn = queue.remove();
if (rn == null) {
if (queue.isEmpty()) {
break;
}
queue.add(null);
continue;
}
if (queue.peek() == null) {
ans.add(rn.val);
}
if (rn.left != null) {
queue.add(rn.left);
}
if (rn.right != null) {
queue.add(rn.right);
}
}
return ans;
}
-> Recursive way easier
public List<Integer> rightSideView(TreeNode root) {
List<Integer> result = new ArrayList<Integer>();
rightView(root, result, 0);
return result;
}
public void rightView(TreeNode curr, List<Integer> result, int currDepth){
if(curr == null){
return;
}
if(currDepth == result.size()){
result.add(curr.val);
}
rightView(curr.right, result, currDepth + 1);
rightView(curr.left, result, currDepth + 1);
}
-----------------------------------------------------------------------------------
7. Left Side view of Binary Tree
public List<Integer> rightSideView(TreeNode root) {
List<Integer>ans=new ArrayList<>();
Queue<TreeNode> queue = new LinkedList<>();
if(root==null){
return ans;
}
TreeNode nn = root;
queue.add(nn);
queue.add(null);
ans.add(root.val);
while (!queue.isEmpty()) {
TreeNode rn = queue.remove();
if (rn == null) {
if (queue.isEmpty()) {
break;
}
ans.add(queue.peek().val);
queue.add(null);
continue;
}
if (rn.left != null) {
queue.add(rn.left);
}
if (rn.right != null) {
queue.add(rn.right);
}
}
return ans;
}
-----------------------------------------------------------------------------------
8. Vertical display of Binary Tree Leetcode-987
private class VDPair implements Comparable<VDPair> {
int val;
int vlevel;
int hlevel;
VDPair(int val, int vlevel, int hlevel) {
this.val = val;
this.vlevel = vlevel;
this.hlevel = hlevel;
}
@Override
public String toString() {
return val + "";
}
@Override
public int compareTo(VDPair other) {
if(this.hlevel==other.hlevel)return this.val-other.val;
return this.hlevel - other.hlevel;
}
}
public List<List<Integer>> VerticalDisplay(TreeNode root) {
HashMap<Integer, ArrayList<VDPair>> map = new HashMap<>();
VerticalDisplay(root, map, 0, 0);
List<List<Integer>>ans=new ArrayList<>();
List<Integer> allkeys = new ArrayList<>(map.keySet());
Collections.sort(allkeys);
for (Integer key : allkeys) {
List<VDPair> list = map.get(key);
Collections.sort(list); // horizontal sorting so that elements will be sorted according to their level
List<Integer>res=new ArrayList<>();
for(int i=0;i<list.size();i++)
res.add(list.get(i).val);
ans.add(res);
}
return ans;
}
private void VerticalDisplay(TreeNode node, HashMap<Integer, ArrayList<VDPair>> map, int vlevel, int hlevel) {
if (node == null) {
return;
}
if (!map.containsKey(vlevel)) {
ArrayList<VDPair> list = new ArrayList<>();
map.put(vlevel, list);
}
VDPair np = new VDPair(node.val, vlevel, hlevel);
map.get(vlevel).add(np);
VerticalDisplay(node.left, map, vlevel - 1, hlevel + 1);
VerticalDisplay(node.right, map, vlevel + 1, hlevel + 1);
}
# For Diagonal Traversal , just put (hlevel-vlevel) in map instead of vlevel only.
#For Top view just put FIRST element of vertical order traversal in ANS Arraylist.
#For Bottom view just put LAST element of vertical order traversal in ANS Arraylist.
//Top View
->
//Function to return a list of nodes visible from the top view
//from left to right in Binary Tree.
static ArrayList<Integer> topView(Node root)
{
ArrayList<Integer> ans = new ArrayList<>();
if(root == null) return ans;
Map<Integer, Integer> map = new TreeMap<>();
Queue<Pair> q = new LinkedList<Pair>();
q.add(new Pair(root, 0));
while(!q.isEmpty()) {
Pair it = q.remove();
int hd = it.hd;
Node temp = it.node;
if(map.get(hd) == null) map.put(hd, temp.data);
if(temp.left != null) {
q.add(new Pair(temp.left, hd - 1));
}
if(temp.right != null) {
q.add(new Pair(temp.right, hd + 1));
}
}
for (Map.Entry<Integer,Integer> entry : map.entrySet()) {
ans.add(entry.getValue());
}
return ans;
}
-> Bottom view
//Function to return a list containing the bottom view of the given tree.
public ArrayList <Integer> bottomView(Node root)
{
ArrayList<Integer> ans = new ArrayList<>();
if(root == null) return ans;
Map<Integer, Integer> map = new TreeMap<>();
Queue<Node> q = new LinkedList<Node>();
root.hd = 0; //hd = the division line tha axis ( left side it is negative, right side it is positive, root side its 0)
q.add(root);
while(!q.isEmpty()) {
Node temp = q.remove();
int hd = temp.hd;
map.put(hd, temp.data); // at last updated hd->(value) it will get the bottom view node
if(temp.left != null) {
temp.left.hd = hd - 1;
q.add(temp.left);
}
if(temp.right != null) {
temp.right.hd = hd + 1;
q.add(temp.right);
}
}
for (Map.Entry<Integer,Integer> entry : map.entrySet()) {
ans.add(entry.getValue());
}
return ans;
}
-----------------------------------------------------------------------------------
9. Lowest Common Ancestor -O(N)
public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
if(root==null){
return null;
}
if(root.val==p.val||root.val==q.val){
return root;
}
TreeNode leftlca=lowestCommonAncestor(root.left,p,q);
TreeNode rightlca=lowestCommonAncestor(root.right,p,q);
if(leftlca!=null&&rightlca!=null){
return root;
}
if(leftlca!=null){
return leftlca;
}
return rightlca;
}
-----------------------------------------------------------------------------------
10. ZigZagLevelOrder Traversal O(n)S(n)
public List<List<Integer>> zigzagLevelOrder(TreeNode root) {
LinkedList<TreeNode> PrimaryS = new LinkedList<>();
LinkedList<TreeNode> helperS = new LinkedList<>();
List<List<Integer>>ans=new ArrayList<>();
if(root==null)return ans;
TreeNode nn = root;
PrimaryS.addFirst(nn);
int count = 0;
List<Integer>res=new ArrayList<>();
while (!PrimaryS.isEmpty()) {
TreeNode rm = PrimaryS.removeFirst();
if (rm != null) {
res.add(rm.val);
if (count % 2 == 0) {
helperS.addFirst(rm.left);
helperS.addFirst(rm.right);
} else {
helperS.addFirst(rm.right);
helperS.addFirst(rm.left);
}
}
if (PrimaryS.isEmpty()) {
count++;
if(res.size()>0)
ans.add(res);
res=new ArrayList<>();
PrimaryS = helperS;
helperS = new LinkedList<>();
}
}
return ans;
}
-> Using one Queue only
public List<List<Integer>> zigzagLevelOrder(TreeNode root) {
Queue<TreeNode> queue = new LinkedList<TreeNode>();
List<List<Integer>> wrapList = new LinkedList<List<Integer>>();
if(root == null) return wrapList;
queue.offer(root);
boolean flag = true; //for changing direction
while(!queue.isEmpty()){
int levelNum = queue.size();
List<Integer> subList = new ArrayList<Integer>(levelNum);
for(int i=0; i<levelNum; i++) {
int index = i;
if(queue.peek().left != null) queue.offer(queue.peek().left);
if(queue.peek().right != null) queue.offer(queue.peek().right);
if(flag == true) subList.add(queue.poll().val);
else subList.add(0, queue.poll().val);
}
flag = !flag;
wrapList.add(subList);
}
return wrapList;
}
-----------------------------------------------------------------------------------
11. Balanced Binary Tree
private class Balpair {
int h = -1;
boolean b = true;
}
private Balpair isbalanced(TreeNode node) {
if (node == null) {
return new Balpair();
}
Balpair lbp = isbalanced(node.left);
Balpair rbp = isbalanced(node.right);
Balpair sbp = new Balpair();
boolean lb = lbp.b;
boolean rb = rbp.b;
int blf = lbp.h - rbp.h;
sbp.b = (lb && rb && (blf == -1 || blf == 0 || blf == 1));
sbp.h = Math.max(lbp.h, rbp.h) + 1;
return sbp;
}
-----------------------------------------------------------------------------------
12. Largest SubTree Sum
private class SubtreePair {
int entireSum = 0;
int maxSumtillnow = Integer.MIN_VALUE;
}
private SubtreePair MaxSubtreeSum1(Node node) {
if (node == null) {
return new SubtreePair();
}
SubtreePair lp = MaxSubtreeSum1(node.left);
SubtreePair rp = MaxSubtreeSum1(node.right);
SubtreePair sp = new SubtreePair();
int lesum = lp.entireSum;
int resum = rp.entireSum;
sp.entireSum = lesum + resum + node.data;
sp.maxSumtillnow = Math.max(sp.entireSum, Math.max(lp.maxSumtillnow, rp.maxSumtillnow));
return sp;
}
--->
static int ms=Integer.MIN_VALUE;
static int msn=0;
public static int NodeWithMaxSubtreeSum(Node node){
int sum=0;
for(Node child:node.children){
sum+=NodeWithMaxSubtreeSum(child);
}
sum+=node.data;
if(sum>ms){
ms=sum;
msn=node.data;
}
return sum;
}
-----------------------------------------------------------------------------------
13. Contruct Binary Tree from preorder and inorder traversal
# without traversing everytime you can just add every element of inorder in a hashmap and get it in constant time
private TreeNode constructPreIn(int[] pre, int plo, int phi, int[] in, int ilo, int ihi) {
if (plo > phi || ilo > ihi) {
return null;
}
TreeNode nn = new TreeNode();
nn.val = pre[plo];
int si = -1; //can use hashmap to get this idx in constant time.
for (int i = ilo; i <= ihi; i++) {
if (in[i] == nn.val) {
si = i;
break;
}
}
int nel = si - ilo;
nn.left = constructPreIn(pre, plo + 1, plo + nel, in, ilo, si - 1);
nn.right = constructPreIn(pre, plo + nel + 1, phi, in, si + 1, ihi);
return nn;
}
-> Using postorder and inorder traversal
private Node constructPostIn(int[] post, int plo, int phi, int[] in, int ilo, int ihi) {
if (plo > phi || ilo > ihi) {
return null;
}
Node nn = new Node();
nn.data = post[phi];
int si = -1;
for (int i = ilo; i <= ihi; i++) {
if (in[i] == nn.data) {
si = i;
break;
}
}
int nel = si - ilo;
nn.left = constructPostIn(post, plo, plo + nel - 1, in, ilo, si - 1);
nn.right = constructPostIn(post, plo + nel, phi - 1, in, si + 1, ihi);
return nn;
}
-----------------------------------------------------------------------------------
14. Symmetric Tree
public boolean isSymmetric(TreeNode left,TreeNode right){
if(left==null|right==null){
return (left==right);
}
if(left.val!=right.val)
return false;
//checking for folding (concealing)
return isSymmetric(left.left,right.right) && isSymmetric(left.right,right.left);
}
-----------------------------------------------------------------------------------
15. Check if 2 trees are mirror of each other
boolean areMirror(Node a, Node b)
{
if (a == null && b == null)
return true;
if (a == null || b == null)
return false;
return a.data == b.data && areMirror(a.left, b.right) && areMirror(a.right, b.left);
}
-----------------------------------------------------------------------------------
16. Preorder (Recursively & Iteratively)
Recursively->
private void preorder(Node node) {
if (node == null) {
return;
}
System.out.print(node.data + " ");
preorder(node.left);
preorder(node.right);
}
Iteratively->
public List<Integer> preorderTraversal(TreeNode root) {
Stack<Pair> st = new Stack<>();
List<Integer>ans=new ArrayList<>();
if(root==null)return ans;
Pair np = new Pair();
np.n = root;
st.push(np);
while (!st.isEmpty()) {
Pair tp = st.peek();
if (!tp.sd) {
ans.add(tp.n.val);
tp.sd = true;
} else if (!tp.ld) {
Pair nlp = new Pair();
nlp.n = tp.n.left;
if (nlp.n != null) {
st.push(nlp);
}
tp.ld = true;
} else if (!tp.rd) {
Pair nrp = new Pair();
nrp.n = tp.n.right;
if (nrp.n != null) {
st.push(nrp);
}
tp.rd = true;
} else
st.pop();
}
return ans;
}
private class Pair {
TreeNode n;
boolean sd;
boolean ld;
boolean rd;
}
-----------------------------------------------------------------------------------
17. All Traversals (Iteratively)
private void AllTraversals(Node root) {
Stack<TPair> st = new Stack<>();
TPair np = new TPair(root, 1);
st.push(np);
String pre = "";
String in = "";
String pos = "";
while (!st.isEmpty()) {
TPair top = st.peek();
if (top.state == 1) { // pre s++ left
pre += top.n.data + " ";
top.state++;
if (top.n.left != null) {
TPair nlp = new TPair(top.n.left, 1);
st.push(nlp);
}
} else if (top.state == 2) { // in s++ right
in += top.n.data + " ";
top.state++;
if (top.n.right != null) {
TPair nrp = new TPair(top.n.right, 1);
st.push(nrp);
}
} else { // pos pop()
pos += top.n.data + " ";
st.pop();
}
}
System.out.println("pre-> " + pre);
System.out.println("in-> " + in);
System.out.println("pos-> " + pos);
}
class TPair {
int state;
Node n;
TPair(Node nn, int s) {
n = nn;
state = s;
}
}
-----------------------------------------------------------------------------------
18. Boundary Traversal
public List<Integer> boundaryOfBinaryTree(TreeNode root) {
List<Integer>list=new ArrayList<>();
if(root==null){
return list;
}
list.add(root.val);
left(root.left,list);
leaf(root,list);
right(root.right,list);
return list;
}
void left(TreeNode node,List<Integer>list){
if(node==null)
return;
if(node.left!=null){
list.add(node.val);
left(node.left,list);
}else if(node.right!=null){
list.add(node.val);
left(node.right,list);
}
}
void leaf(TreeNode node,List<Integer>list){
if(node==null)
return;
leaf(node.left,list);
if(node.left==null&&node.right==null){
list.add(node.val);
}
leaf(node.right,list);
}
void right(TreeNode node,List<Integer>list){
if(node==null)
return;
if(node.right!=null){
right(node.right,list);
list.add(node.val);
}else if(node.left!=null){
right(node.left,list);
list.add(node.val);
}
}
-----------------------------------------------------------------------------------
19. Root-to-leaf has pathSum to targeted val
public boolean hasPathSum(TreeNode node, int targetSum) {
if(node==null){
return false;
}
if(node.left==null && node.right==null && targetSum-node.val==0){
return true;
}
boolean lp=hasPathSum(node.left,targetSum-node.val);
boolean rp=hasPathSum(node.right,targetSum-node.val);
return lp||rp;
}
-----------------------------------------------------------------------------------
20. Check for Sum Tree
pair checkSumTree(Node node){
if(node==null){
return new pair();
}
pair lp=checkSumTree(node.left);
pair rp=checkSumTree(node.right);
pair sp=new pair();
if(node.data==lp.entiresum+rp.entiresum && lp.b && rp.b){
sp.b=true;
}else if(node.left==null&&node.right==null){
sp.b=true;
}else
sp.b=false;
sp.entiresum=lp.entiresum+rp.entiresum+node.data;
return sp;
}
class pair{
int entiresum=0;
boolean b=true;
}
-----------------------------------------------------------------------------------
21. Convert Binary Tree into SumTree
public int SumTreeConvert(Node node){
if(node==null){
return 0;
}
int lsum=SumTreeConvert(node.left);
int rsum=SumTreeConvert(node.right);
int temp=node.data;
node.data=lsum+rsum;
return temp+node.data;
}
-----------------------------------------------------------------------------------
22. Leaf at same level
boolean leafSameLevel(Node node,int level,Set<Integer>set){
if(node==null){
return true;
}
if(node.left==null&&node.right==null){
set.add(level);
if(set.size()>1){
return false;
}else
return true;
}
boolean l=leafSameLevel(node.left,level+1,set);
boolean r=leafSameLevel(node.right,level+1,set);
return l&&r;
}
-----------------------------------------------------------------------------------
23. Sum of the Longest Bloodline of a Tree (Sum of nodes on the longest path from root to leaf node)
public void SumoflongestR2L(Node node,int level,int sum,int[]arr){
if(node==null){
return;
}
if(node.left==null&&node.right==null){
if(level>arr[0]){
arr[0]=level;
arr[1]=sum+node.data;
}else if(level==arr[0]){
arr[1]=Math.max(arr[1],sum+node.data);
}
return;
}
SumoflongestR2L(node.left,level+1,sum+node.data,arr);
SumoflongestR2L(node.right,level+1,sum+node.data,arr);
}
-----------------------------------------------------------------------------------
24. Min distance between two given nodes of a Binary Tree.
Root to node distance->
private static int findDistance(Node1 root, int n) {
if (root == null)
return -1;
if (root.value == n)
return 0;
int left = findDistance(root.left, n);
int right = findDistance(root.right, n);
if(left==-1 && right==-1)
return -1;
return 1+Math.max(left, right);
}
int findDist(Node root, int a, int b) {
int item=lca(root,a,b);
return root2node(root,a)+root2node(root,b)-2*(root2node(root,item));
}
int root2node(Node node,int val){
if(node==null){
return -1;
}
int dis=-1;
if((node.data==val)||(dis=root2node(node.left,val))>=0||(dis=root2node(node.right,val))>=0)
return dis+1;
return dis; //if not found yet;
}
int lca(Node node,int a,int b){
if(node==null){
return -1;
}
if(node.data==a||node.data==b){
return node.data;
}
int l=lca(node.left,a,b);
int r=lca(node.right,a,b);
if(l!=-1&&r!=-1){
return node.data;
}
if(l!=-1){
return l;
}
return r;
}
-----------------------------------------------------------------------------------
25. All Nodes Distance K in Binary Tree (Leetcode->863.)
//DryRun for best understanding
public List<Integer> distanceK(TreeNode node, TreeNode target, int k) {
List<Integer>ans=new ArrayList<>();
if(node==null)return ans;
//it will collect the path from target to root.
ArrayList<TreeNode>path=new ArrayList<>();
node2rootpath(node,target.val,path);
for(int i=0;i<path.size();i++){
CollectKlevelDown(path.get(i),k-i,i==0?null:path.get(i-1),ans);
//sending a blocker so that //elements which are already collected in ans do not get //collected again due to same level.
}
return ans;
}
public boolean node2rootpath(TreeNode node,int item,ArrayList<TreeNode>list){
if(node==null){
return false;
}
if(node.val==item){
list.add(node);
return true;
}
boolean lc=node2rootpath(node.left,item,list);
if(lc){
list.add(node);
return true;
}
boolean rc=node2rootpath(node.right,item,list);
if(rc){
list.add(node);
return true;
}
return false;
}
public void CollectKlevelDown(TreeNode node,int k,TreeNode blocker,List<Integer>ans){
if(node==null||k<0||node==blocker){
return;
}
if(k==0){
ans.add(node.val);
}
CollectKlevelDown(node.left,k-1,blocker,ans);
CollectKlevelDown(node.right,k-1,blocker,ans);
}
-> Striver explaination
* Mark each node to its parent to traverse upwards
* We will do a BFS traversal starting from the target node
* As long as we have not seen our node previously, Traverse up, left, right until reached Kth distance
* when reached Kth distance, break out of BFS loop and remaining node's values in our queue is our result
->
private void markParents(TreeNode root, Map<TreeNode, TreeNode> parent_track, TreeNode target) {
Queue<TreeNode> queue = new LinkedList<TreeNode>();
queue.offer(root);
while(!queue.isEmpty()) {
TreeNode current = queue.poll();
if(current.left != null) {
parent_track.put(current.left, current);
queue.offer(current.left);
}
if(current.right != null) {
parent_track.put(current.right, current);
queue.offer(current.right);
}
}
}
public List<Integer> distanceK(TreeNode root, TreeNode target, int k) {
Map<TreeNode, TreeNode> parent_track = new HashMap<>();
markParents(root, parent_track, root);
Map<TreeNode, Boolean> visited = new HashMap<>();
Queue<TreeNode> queue = new LinkedList<TreeNode>();
queue.offer(target);
visited.put(target, true);
int curr_level = 0;
while(!queue.isEmpty()) { /*Second BFS to go upto K level from target node and using our hashtable info*/
int size = queue.size();
if(curr_level == k) break;
curr_level++;
for(int i=0; i<size; i++) {
TreeNode current = queue.poll();
if(current.left != null && visited.get(current.left) == null) {
queue.offer(current.left);
visited.put(current.left, true);
}
if(current.right != null && visited.get(current.right) == null ) {
queue.offer(current.right);
visited.put(current.right, true);
}
if(parent_track.get(current) != null && visited.get(parent_track.get(current)) == null) {
queue.offer(parent_track.get(current));
visited.put(parent_track.get(current), true);
}
}
}
List<Integer> result = new ArrayList<>();
while(!queue.isEmpty()) {
TreeNode current = queue.poll();
result.add(current.val);
}
return result;
}
-----------------------------------------------------------------------------------
26. Flip Equivalent Binary Trees (Isomorphic Trees)
public boolean flipEquiv(TreeNode n1, TreeNode n2) {
if(n1==null||n2==null){
return n1==n2;
}
if(n1.val!=n2.val)return false;
boolean o1=flipEquiv(n1.left,n2.left);
boolean o2=flipEquiv(n1.right,n2.right);
boolean o3=flipEquiv(n1.left,n2.right);
boolean o4=flipEquiv(n1.right,n2.left);
return (o1&&o2)||(o3&&o4);
}
-----------------------------------------------------------------------------------
27. Print all K Sum paths
static Vector<Integer> path = new Vector<Integer>();
// This function prints all paths that have sum k
static void printKPathUtil(Node root, int k)
{
if (root == null)
return;
path.add(root.data);
printKPathUtil(root.left, k);
printKPathUtil(root.right, k);
int f = 0;
for (int j = path.size() - 1; j >= 0; j--)
{
f += path.get(j);