-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTreeBreadthFirstSearch.py
More file actions
478 lines (354 loc) · 10.8 KB
/
TreeBreadthFirstSearch.py
File metadata and controls
478 lines (354 loc) · 10.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
from __future__ import print_function
from operator import le, length_hint
import queue
# Problem Statement
'''
Given a binary tree, populate an array to represent its level-by-level traversal.
You should populate the values of all nodes of each level
from left to right in separate sub-arrays.
'''
class TreeNode:
def __init__(self, val):
self.val = val
self.left, self.right = None, None
def traverse(root):
myQueue = [root]
result = []
while myQueue:
levelArray = []
level_length = len(myQueue)
for _ in range(level_length):
curNode = myQueue.pop(0)
levelArray.append(curNode.val)
if curNode.left:
myQueue.append(curNode.left)
if curNode.right:
myQueue.append(curNode.right)
result.append(levelArray)
return result
def main():
root = TreeNode(12)
root.left = TreeNode(7)
root.right = TreeNode(1)
root.left.left = TreeNode(9)
root.right.left = TreeNode(10)
root.right.right = TreeNode(5)
print("Level order traversal: " + str(traverse(root)))
main()
# Reverse Level Order Traversal
'''
Problem Statement#
Given a binary tree, populate an array to represent its level-by-level traversal in reverse order, i.e.,
the lowest level comes first.
You should populate the values of all nodes in each level from left to right in separate sub-arrays.
'''
def traverse(root):
myQueue = [root]
result = []
while myQueue:
levelArray = []
level_length = len(myQueue)
for _ in range(level_length):
curNode = myQueue.pop(0)
levelArray.append(curNode.val)
if curNode.left:
myQueue.append(curNode.left)
if curNode.right:
myQueue.append(curNode.right)
result.append(levelArray)
return result[::-1]
def main():
root = TreeNode(12)
root.left = TreeNode(7)
root.right = TreeNode(1)
root.left.left = TreeNode(9)
root.right.left = TreeNode(10)
root.right.right = TreeNode(5)
print("Reverse level order traversal: " + str(traverse(root)))
main()
# Zigzag Traversal
'''
Given a binary tree, populate an array to represent its zigzag level order traversal.
You should populate the values of all nodes of the first level from left to right,
then right to left for the next level and keep alternating in the
same manner for the following levels.
'''
def traverse(root):
result = []
queue = [root]
isLeft = True
while queue:
currentLevel = []
length = len(queue)
for _ in range(length):
node = queue.pop(0)
currentLevel.append(node.val)
if node.left:
queue.append(node.left)
if node.right:
queue.append(node.right)
if isLeft == False:
result.append(currentLevel[::-1])
else:
result.append(currentLevel)
# flip bool
isLeft = not isLeft
return result
def main():
root = TreeNode(12)
root.left = TreeNode(7)
root.right = TreeNode(1)
root.left.left = TreeNode(9)
root.right.left = TreeNode(10)
root.right.right = TreeNode(5)
root.right.left.left = TreeNode(20)
root.right.left.right = TreeNode(17)
print("Zigzag traversal: " + str(traverse(root)))
main()
# Level Averages in a Binary Tree
'''
Given a binary tree,
populate an array to represent the averages of all of its levels.
'''
def find_level_averages(root):
result = []
queue = [root]
while queue:
length = len(queue)
levelValue = 0
for _ in range(length):
node = queue.pop(0)
levelValue += node.val
if node.left:
queue.append(node.left)
if node.right:
queue.append(node.right)
result.append(levelValue/length)
return result
def main():
root = TreeNode(12)
root.left = TreeNode(7)
root.right = TreeNode(1)
root.left.left = TreeNode(9)
root.left.right = TreeNode(2)
root.right.left = TreeNode(10)
root.right.right = TreeNode(5)
print("Level averages are: " + str(find_level_averages(root)))
main()
# Minimum Depth of a Binary Tree
'''
Find the minimum depth of a binary tree.
The minimum depth is the number of nodes along
the shortest path from the root node to the nearest leaf node.
'''
def find_minimum_depth(root):
# TODO: Write your code here
queue = [root]
minDepth = 0
while True:
length = len(queue)
minDepth += 1
for _ in range(length):
node = queue.pop(0)
if not node.left and not node.right:
return minDepth
if node.left:
queue.append(node.left)
if node.right:
queue.append(node.right)
def main():
root = TreeNode(12)
root.left = TreeNode(7)
root.right = TreeNode(1)
root.right.left = TreeNode(10)
root.right.right = TreeNode(5)
print("Tree Minimum Depth: " + str(find_minimum_depth(root)))
root.left.left = TreeNode(9)
root.right.left.left = TreeNode(11)
print("Tree Minimum Depth: " + str(find_minimum_depth(root)))
main()
# Level Order Successor
'''
Given a binary tree and a node,
find the level order successor of the given node in the tree.
The level order successor is the node that appears right after
the given node in the level order traversal.
'''
def find_successor(root, key):
# TODO: Write your code here
queue = [root]
result = []
ind = None
while queue:
length = len(queue)
for _ in range(length):
node = queue.pop(0)
result.append(node)
if node.val == key:
ind = len(result) - 1
if node.left:
queue.append(node.left)
if node.right:
queue.append(node.right)
if len(result) -1 == ind:
return -1
return result[ind+1]
def main():
root = TreeNode(1)
root.left = TreeNode(2)
root.right = TreeNode(3)
root.left.left = TreeNode(4)
root.left.right = TreeNode(5)
result = find_successor(root, 3)
if result:
print(result.val)
root = TreeNode(12)
root.left = TreeNode(7)
root.right = TreeNode(1)
root.left.left = TreeNode(9)
root.right.left = TreeNode(10)
root.right.right = TreeNode(5)
result = find_successor(root, 9)
if result:
print(result.val)
result = find_successor(root, 12)
if result:
print(result.val)
main()
# Connect Level Order Siblings
'''
Given a binary tree, connect each node with its level order successor.
The last node of each level should point to a null node.
'''
class TreeNode:
def __init__(self, val):
self.val = val
self.left, self.right, self.next = None, None, None
# level order traversal using 'next' pointer
def print_level_order(self):
nextLevelRoot = self
while nextLevelRoot:
current = nextLevelRoot
nextLevelRoot = None
while current:
print(str(current.val) + " ", end='')
if not nextLevelRoot:
if current.left:
nextLevelRoot = current.left
elif current.right:
nextLevelRoot = current.right
current = current.next
print()
def connect_level_order_siblings(root):
queue = [root]
while queue:
length = len(queue)
levelArray = []
for i in range(length):
node = queue.pop(0)
levelArray.append(node)
if node.left:
queue.append(node.left)
if node.right:
queue.append(node.right)
if i == length - 1:
node.next = None
for j in range(len(levelArray) - 1):
levelArray[j].next = levelArray[j+1]
return root
def main():
root = TreeNode(12)
root.left = TreeNode(7)
root.right = TreeNode(1)
root.left.left = TreeNode(9)
root.right.left = TreeNode(10)
root.right.right = TreeNode(5)
connect_level_order_siblings(root)
print("Level order traversal using 'next' pointer: ")
root.print_level_order()
main()
# Connect All Level Order Siblings
'''
Given a binary tree,
connect each node with its level order successor.
The last node of each level
should point to the first node of the next level.
'''
class TreeNode:
def __init__(self, val):
self.val = val
self.left, self.right, self.next = None, None, None
# tree traversal using 'next' pointer
def print_tree(self):
print("Traversal using 'next' pointer: ", end='')
current = self
while current:
print(str(current.val) + " ", end='')
current = current.next
def connect_all_siblings(root):
# TODO: Write your code here
queue = [root]
while queue:
levelArray = []
length = len(queue)
for i in range(length):
node = queue.pop(0)
levelArray.append(node)
if node.left:
queue.append(node.left)
if node.right:
queue.append(node.right)
if i == length - 1 and len(queue) != 0:
node.next = queue[0]
for j in range(length - 1):
levelArray[j].next = levelArray[j+1]
return root
def main():
root = TreeNode(12)
root.left = TreeNode(7)
root.right = TreeNode(1)
root.left.left = TreeNode(9)
root.right.left = TreeNode(10)
root.right.right = TreeNode(5)
connect_all_siblings(root)
root.print_tree()
main()
# Right View of a Binary Tree
'''
Given a binary tree, return an array containing nodes in its right view.
The right view of a binary tree is the set of nodes visible
when the tree is seen from the right side.
'''
class TreeNode:
def __init__(self, val):
self.val = val
self.left, self.right = None, None
def tree_right_view(root):
result = []
# TODO: Write your code here
queue = [root]
while queue:
levelArray = []
length = len(queue)
for _ in range(length):
node = queue.pop(0)
levelArray.append(node)
if node.left:
queue.append(node.left)
if node.right:
queue.append(node.right)
result.append(levelArray[-1])
return result
def main():
root = TreeNode(12)
root.left = TreeNode(7)
root.right = TreeNode(1)
root.left.left = TreeNode(9)
root.right.left = TreeNode(10)
root.right.right = TreeNode(5)
root.left.left.left = TreeNode(3)
result = tree_right_view(root)
print("Tree right view: ")
for node in result:
print(str(node.val) + " ", end='')
main()