-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path1.py
79 lines (63 loc) · 1.58 KB
/
1.py
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
class Node:
def__init_(self,val):
self.val = val
self.left = left
self.right = None
def bfs(root):
if rootisnone:
return
visited []
queue = [root]
whilequeue:
node = queue.pop(0)
visited.append(node.val)
ifnode.left:
queue.append(node.left)
ifnode.right:
queue.append(node.right)
returnvisited
# example binary tree
# 1
# / \
# 2 3
# / \ / \
# 4 5 6 7
root = Node(1)
root.left = Node(2)
root.right = Node(3)
root.left.left = Node(4)
root.left.right = Node(5)
root.right.left = Node(6)
root.right.right = Node(7)
print(bfs(root)) # Output: [1, 2, 3, 4, 5, 6, 7]
# def__init__(self, val):
# self.val = val
# self.left = None
# self.right = None
# defbfs(root):
# ifrootisNone:
# return
# visited = []
# queue = [root]
# whilequeue:
# node = queue.pop(0)
# visited.append(node.val)
# ifnode.left:
# queue.append(node.left)
# ifnode.right:
# queue.append(node.right)
# returnvisited
# # example binary tree
# # 1
# # / \
# # 2 3
# # / \ / \
# # 4 5 6 7
# root = Node(1)
# root.left = Node(2)
# root.right = Node(3)
# root.left.left = Node(4)
# root.left.right = Node(5)
# root.right.left = Node(6)
# root.right.right = Node(7)
# print(bfs(root)) # Output: [1, 2, 3, 4, 5, 6, 7]