Repository navigation
Expand file tree
/
Copy pathTree.py
More file actions
734 lines (629 loc) · 20.8 KB
/
Copy pathTree.py
File metadata and controls
734 lines (629 loc) · 20.8 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
#!/usr/bin/env python
from collections import deque
class Tree(object):
class Node(object):
def __init__(self, v, l=None, r=None):
self.value = v
self.lChild = l
self.rChild = r
def __init__(self):
self.root = None
def levelOrderBinaryTree(self, arr):
self.root = self.levelOrderBinaryTreeUtil(arr, 0)
def levelOrderBinaryTreeUtil(self, arr, start):
size = len(arr)
curr = self.Node(arr[start])
left = 2 * start + 1
right = 2 * start + 2
if left < size:
curr.lChild = self.levelOrderBinaryTreeUtil(arr, left)
if right < size:
curr.rChild = self.levelOrderBinaryTreeUtil(arr, right)
return curr
def InsertNode(self, value):
self.root = self.InsertNodeUtil(self.root, value)
def InsertNodeUtil(self, node, value):
if node == None:
node = self.Node(value)
else:
if node.value > value:
node.lChild = self.InsertNodeUtil(node.lChild, value)
else:
node.rChild = self.InsertNodeUtil(node.rChild, value)
return node
def PrintPreOrder(self):
self.PrintPreOrderUtil(self.root)
def PrintPreOrderUtil(self, node):
# pre order
if node != None:
print (node.value),
self.PrintPreOrderUtil(node.lChild)
self.PrintPreOrderUtil(node.rChild)
def NthPreOrder(self, index):
count = [0]
self.NthPreOrderUtil(self.root, index, count)
def NthPreOrderUtil(self, node, index, count):
# pre order
if node != None:
count[0] += 1
if count[0] == index:
print (node.value),
self.NthPreOrderUtil(node.lChild, index, count)
self.NthPreOrderUtil(node.rChild, index, count)
def PrintPostOrder(self):
self.PrintPostOrderUtil(self.root)
def PrintPostOrderUtil(self, node):
# post order
if node != None:
self.PrintPostOrderUtil(node.lChild)
self.PrintPostOrderUtil(node.rChild)
print (node.value),
def NthPostOrder(self, index):
count = [0]
self.NthPostOrderUtil(self.root, index, count)
def NthPostOrderUtil(self, node, index, count):
# post order
if node != None:
self.NthPostOrderUtil(node.lChild, index, count)
self.NthPostOrderUtil(node.rChild, index, count)
count[0] += 1
if count[0] == index:
print (node.value),
def PrintInOrder(self):
self.PrintInOrderUtil(self.root)
def PrintInOrderUtil(self, node):
# In order
if node != None:
self.PrintInOrderUtil(node.lChild)
print (node.value),
self.PrintInOrderUtil(node.rChild)
def NthInOrder(self, index):
count = [0]
self.NthInOrderUtil(self.root, index, count)
def NthInOrderUtil(self, node, index, count):
if node != None:
self.NthInOrderUtil(node.lChild, index, count)
count[0] += 1
if count[0] == index:
print (node.value),
self.NthInOrderUtil(node.rChild, index, count)
def PrintBredthFirst(self):
que = deque([])
temp = None
if self.root != None:
que.append(self.root)
while len(que) != 0:
temp = que.popleft()
print (temp.value),
if temp.lChild != None:
que.append(temp.lChild)
if temp.rChild != None:
que.append(temp.rChild)
def PrintDepthFirst(self):
stk = []
if self.root != None:
stk.append(self.root)
while stk.isEmpty() == False:
temp = stk.pop()
print (temp.value),
if temp.rChild != None:
stk.append(temp.rChild)
if temp.lChild != None:
stk.append(temp.lChild)
def Find(self, value):
curr = self.root
while curr != None:
if curr.value == value:
return True
elif curr.value > value:
curr = curr.lChild
else:
curr = curr.rChild
return False
def FindMin(self):
node = self.root
if node == None:
raise RuntimeError("ListEmptyException")
while node.lChild != None:
node = node.lChild
return node.value
def FindMax(self):
node = self.root
if node == None:
raise RuntimeError("ListEmptyException")
while node.rChild != None:
node = node.rChild
return node.value
def FindMaxUtil(self, curr):
node = curr
if node == None:
return None
while node.rChild != None:
node = node.rChild
return node
def FindMinUtil(self, curr):
node = curr
if node == None:
return None
while node.lChild != None:
node = node.lChild
return node
def Free(self):
self.root = None
def DeleteNode(self, value):
self.root = self.DeleteNodeUtil(self.root, value)
def DeleteNodeUtil(self, node, value):
temp = None
if node != None:
if node.value == value:
if node.lChild == None and node.rChild == None:
return None
else:
if node.lChild == None:
temp = node.rChild
return temp
if node.rChild == None:
temp = node.lChild
return temp
maxnode = self.FindMaxUtil(node.lChild)
node.value = maxnode.value
node.lChild = self.DeleteNodeUtil(node.lChild, maxnode.value)
else:
if node.value > value:
node.lChild = self.DeleteNodeUtil(node.lChild, value)
else:
node.rChild = self.DeleteNodeUtil(node.rChild, value)
return node
def TreeDepth(self):
return self.TreeDepthUtil(self.root)
def TreeDepthUtil(self, root):
if root == None:
return 0
else:
lDepth = self.TreeDepthUtil(root.lChild)
rDepth = self.TreeDepthUtil(root.rChild)
if lDepth > rDepth:
return lDepth + 1
else:
return rDepth + 1
def isEqual(self, T2):
return self.Identical(self.root, T2.root)
def Identical(self, node1, node2):
if node1 == None and node2 == None:
return True
elif node1 == None or node2 == None:
return False
else:
return (self.Identical(node1.lChild, node2.lChild) and self.Identical(node1.rChild, node2.rChild) and (node1.value == node2.value))
def Ancestor(self, first, second):
if first > second:
temp = first
first = second
second = temp
curr = self.AncestorUtil(self.root, first, second)
if curr == None:
retval = sys.maxint
else :
retval = curr.value
return retval
def AncestorUtil(self, curr, first, second):
if curr == None:
return None
if curr.value > first and curr.value > second:
return self.AncestorUtil(curr.lChild, first, second)
if curr.value < first and curr.value < second:
return self.AncestorUtil(curr.rChild, first, second)
return curr
def CopyTree(self):
tree2 = Tree()
tree2.root = self.CopyTreeUtil(self.root)
return tree2
def CopyTreeUtil(self, curr):
if curr != None:
temp = self.Node(curr.value)
temp.lChild = self.CopyTreeUtil(curr.lChild)
temp.rChild = self.CopyTreeUtil(curr.rChild)
return temp
else:
return None
def CopyMirrorTree(self):
tree2 = Tree()
tree2.root = self.CopyMirrorTreeUtil(self.root)
return tree2
def CopyMirrorTreeUtil(self, curr):
if curr != None:
temp = self.Node(curr.value)
temp.rChild = self.CopyMirrorTreeUtil(curr.lChild)
temp.lChild = self.CopyMirrorTreeUtil(curr.rChild)
return temp
else:
return None
def numNodes(self):
return self.numNodesUtil(self.root)
def numNodesUtil(self, curr):
if curr == None:
return 0
else:
return (1 + self.numNodesUtil(curr.rChild) + self.numNodesUtil(curr.lChild))
def numFullNodesBT(self):
return self.numFullNodesBTUtil(self.root)
def numFullNodesBTUtil(self, curr):
if curr == None:
return 0
count = self.numFullNodesBTUtil(curr.rChild) + self.numFullNodesBTUtil(curr.lChild)
if curr.rChild != None and curr.lChild != None:
count += 1
return count
def maxLengthPathBT(self):
return self.maxLengthPathBTUtil(self.root)
def maxLengthPathBTUtil(self, curr):
# diameter
if curr == None:
return 0
leftPath = self.TreeDepthUtil(curr.lChild)
rightPath = self.TreeDepthUtil(curr.rChild)
maxpath = leftPath + rightPath + 1
leftMax = self.maxLengthPathBTUtil(curr.lChild)
rightMax = self.maxLengthPathBTUtil(curr.rChild)
if leftMax > maxpath:
maxpath = leftMax
if rightMax > max:
maxpath = rightMax
return maxpath
def numLeafNodes(self):
return self.numLeafNodesUtil(self.root)
def numLeafNodesUtil(self, curr):
if curr == None:
return 0
if curr.lChild == None and curr.rChild == None:
return 1
else:
return (self.numLeafNodesUtil(curr.rChild) + self.numLeafNodesUtil(curr.lChild))
def sumAllBT(self):
return self.sumAllBTUtil(self.root)
def sumAllBTUtil(self, curr):
if curr == None:
return 0
rightSum = self.sumAllBTUtil(curr.rChild)
leftSum = self.sumAllBTUtil(curr.lChild)
finalsum = rightSum + leftSum + curr.value
return finalsum
def iterativePreOrder(self):
stk = []
if self.root != None:
stk.append(self.root)
while len(stk) != 0:
curr = stk.pop()
print (curr.value),
if curr.rChild != None:
stk.append(curr.rChild)
if curr.lChild != None:
stk.append(curr.lChild)
def iterativePostOrder(self):
stk = []
visited = []
if self.root != None:
stk.append(self.root)
visited.append(0)
while len(stk) != 0:
curr = stk.pop()
vtd = visited.pop()
if vtd == 1:
print (curr.value),
else:
stk.append(curr)
visited.append(1)
if curr.rChild != None:
stk.append(curr.rChild)
visited.append(0)
if curr.lChild != None:
stk.append(curr.lChild)
visited.append(0)
def iterativeInOrder(self):
stk = []
visited = []
if self.root != None:
stk.append(self.root)
visited.append(0)
while len(stk) != 0:
curr = stk.pop()
vtd = visited.pop()
if vtd == 1:
print (curr.value),
else:
if curr.rChild != None:
stk.append(curr.rChild)
visited.append(0)
stk.append(curr)
visited.append(1)
if curr.lChild != None:
stk.append(curr.lChild)
visited.append(0)
def isBST3(self, root):
if root == None:
return True
if root.lChild != None and self.FindMax(root.lChild).value > root.value:
return False
if root.rChild != None and self.FindMin(root.rChild).value <= root.value:
return False
return (self.isBST3(root.lChild) and self.isBST3(root.rChild))
def isBST(self):
return self.isBSTUtil(self.root, -999999, 999999)
def isBSTUtil(self, curr, minval, maxval):
if curr == None:
return True
if curr.value < minval or curr.value > maxval:
return False
return self.isBSTUtil(curr.lChild, minval, curr.value) and self.isBSTUtil(curr.rChild, curr.value, maxval)
def isBST2(self):
count = [0]
return self.isBST2Util(self.root, count)
def isBST2Util(self, curr, count):
# in order traversal
ret = bool()
if curr != None:
ret = self.isBST2Util(curr.lChild, count)
if not ret:
return False
if count[0] > curr.value:
return False
count[0] = curr.value
ret = self.isBST2Util(curr.rChild, count)
if not ret:
return False
return True
def printAllPath(self):
stk = []
self.printAllPathUtil(self.root, stk)
def printAllPathUtil(self, curr, stk):
if curr == None:
return
stk.append(curr.value)
if curr.lChild == None and curr.rChild == None:
print (stk)
stk.pop()
return
self.printAllPathUtil(curr.rChild, stk)
self.printAllPathUtil(curr.lChild, stk)
stk.pop()
def LCA(self, first, second):
ans = self.LCAUtil(self.root, first, second)
if ans != None:
return ans.value
else:
return sys.maxint
def LCAUtil(self, curr, first, second):
if curr == None:
return None
if curr.value == first or curr.value == second:
return curr
left = self.LCAUtil(curr.lChild, first, second)
right = self.LCAUtil(curr.rChild, first, second)
if left != None and right != None:
return curr
elif left != None:
return left
else:
return right
def LcaBST(self, first, second):
curr = self.LcaBSTUtil(self.root, first, second)
if(curr == None):
raise RuntimeError("LCAMissing")
return curr.value
def LcaBSTUtil(self, curr, first, second):
if curr == None:
return None
if curr.value > first and curr.value > second:
return self.LcaBSTUtil(curr.lChild, first, second)
if curr.value < first and curr.value < second:
return self.LcaBSTUtil(curr.rChild, first, second)
return curr
def trimOutsideRange(self, minval, maxval):
self.trimOutsideRangeUtil(self.root, minval, maxval)
def trimOutsideRangeUtil(self, curr, minval, maxval):
if curr == None:
return None
curr.lChild = self.trimOutsideRangeUtil(curr.lChild, minval, maxval)
curr.rChild = self.trimOutsideRangeUtil(curr.rChild, minval, maxval)
if curr.value < minval:
return curr.rChild
if curr.value > maxval:
return curr.lChild
return curr
def printInRange(self, minval, maxval):
self.printInRangeUtil(self.root, minval, maxval)
def printInRangeUtil(self, root, minval, maxval):
if root == None:
return
self.printInRangeUtil(root.lChild, minval, maxval)
if root.value >= minval and root.value <= maxval:
print (root.value),
self.printInRangeUtil(root.rChild, minval, maxval)
def FloorBST(self, val):
curr = self.root
floor = sys.maxint
while curr != None:
if curr.value == val:
floor = curr.value
break
elif curr.value > val:
curr = curr.lChild
else:
floor = curr.value
curr = curr.rChild
return floor
def CeilBST(self, val):
curr = self.root
ceil = -1 * (sys.maxunicode)
while curr != None:
if curr.value == val:
ceil = curr.value
break
elif curr.value > val:
ceil = curr.value
curr = curr.lChild
else:
curr = curr.rChild
return ceil
def findMaxBT(self):
ans = self.findMaxBTUtil(self.root)
return ans
def findMaxBTUtil(self, curr):
if curr == None:
return -1 * sys.maxint
maxval = curr.value
left = self.findMaxBTUtil(curr.lChild)
right = self.findMaxBTUtil(curr.rChild)
if left > maxval:
maxval = left
if right > maxval:
maxval = right
return maxval
def searchBT(self, root, value):
if root == None:
return False
if root.value == value:
return True
left = self.searchBT(root.lChild, value)
if left:
return True
right = self.searchBT(root.rChild, value)
if right:
return True
return False
def CreateBinaryTree(self, arr):
self.root = self.CreateBinaryTreeUtil(arr, 0, len(arr)-1)
def CreateBinaryTreeUtil(self, arr, start, end):
if start > end:
return None
mid = (start + end) / 2
curr = self.Node(arr[mid])
curr.lChild = self.CreateBinaryTreeUtil(arr, start, mid - 1)
curr.rChild = self.CreateBinaryTreeUtil(arr, mid + 1, end)
return curr
def treeToList(self):
return self.treeToListRec(self.root)
def treeToListRec(self, curr):
if curr == None:
return None
if curr.lChild == None and curr.rChild == None:
curr.lChild = curr
curr.rChild = curr
return curr
if curr.lChild != None:
Head = self.treeToListRec(curr.lChild)
Tail = Head.lChild
curr.lChild = Tail
Tail.rChild = curr
else:
Head = curr
if curr.rChild != None:
tempHead = self.treeToListRec(curr.rChild)
Tail = tempHead.lChild
curr.rChild = tempHead
tempHead.lChild = curr
else:
Tail = curr
Head.lChild = Tail
Tail.rChild = Head
return Head
# =======================================================================
# arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
# t2 = Tree()
# t2.levelOrderBinaryTree(arr)
# =======================================================================
# =======================================================================
# t = Tree()
# arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
# # t.levelOrderBinaryTree(arr)
# t.InsertNode(5)
# t.InsertNode(3)
# t.InsertNode(4)
# t.InsertNode(2)
# t.InsertNode(1)
# t.InsertNode(8)
# t.InsertNode(7)
# t.InsertNode(9)
# # print (t.CeilBST(6))
# t.printAllPath()
# print("")
# t.iterativeInOrder()
# print("")
# t.PrintInOrder()
# print("")
# t.iterativePreOrder()
# print("")
# t.PrintPreOrder()
# print("")
# t.iterativePostOrder()
# print("")
# t.PrintPostOrder()
# print("")
#
# t.PrintBredthFirst()
# # t.treeToList();
# print ( t.LCA(10, 3) )
# =======================================================================
arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
t2 = Tree()
# t2.levelOrderBinaryTree(arr)
# =======================================================================
# t2.InsertNode(5)
# t2.InsertNode(3)
# t2.InsertNode(4)
# t2.InsertNode(2)
# t2.InsertNode(1)
# t2.InsertNode(8)
# t2.InsertNode(7)
# t2.InsertNode(9)
# =======================================================================
# print t2.Ancestor(1, 10)
# print t2.CeilBST(7)
# print t2.FloorBST(12)
t2.CreateBinaryTree(arr)
t2.PrintInOrder()
print ""
t2.iterativeInOrder()
print ""
t2.PrintPostOrder()
print ""
t2.iterativePostOrder()
print ""
t2.PrintPreOrder()
print ""
t2.iterativePreOrder()
# t2.DeleteNode(8)
# =======================================================================
# t3 = t2.CopyMirrorTree()
# t2.PrintInOrder()
# print ""
# t3.PrintInOrder()
# print t2.Find(18)
# print t2.findMaxBT()
# print t2.FindMax()
# print t2.FindMin()
# t4 = t2.CopyTree()
# t4.PrintInOrder()
# print ""
# t2.PrintInOrder()
# print ""
# t2.PrintPostOrder()
# print ""
# t2.PrintPreOrder()
# print ""
# print t2.numNodes()
# print t2.NthInOrder(2)
# print t2.NthPostOrder(2)
# print t2.NthPreOrder(2)
# print t2.isEqual(t4)
# print t2.TreeDepth()
# print t2.maxLengthPathBT()
# print t2.numFullNodesBT()
# print t2.isBST()
# print t2.isBST2()
# print t2.numLeafNodes()
# print t2.numNodes()
# print t2.printInRange(4, 7)
# print t2.trimOutsideRange(3, 8)
# print t2.PrintInOrder()
# =======================================================================