-
Notifications
You must be signed in to change notification settings - Fork 0
/
breadth_first_search.py
40 lines (32 loc) · 953 Bytes
/
breadth_first_search.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
from binary_tree import BinaryTree, TreeNode
from collections import deque
def breadthFirstSearch(root):
q = deque()
q.append(root)
while q:
node = q.popleft()
print("{} ".format(node.val), end="")
if node.left:
q.append(node.left)
if node.right:
q.append(node.right)
print()
def depthFirstSearch(root):
if root:
print("{} ".format(root.val), end="")
if root.left:
depthFirstSearch(root.left)
if root.right:
depthFirstSearch(root.right)
if __name__ == "__main__":
tree = BinaryTree()
D = TreeNode("D", TreeNode("C"), TreeNode("E"))
B = TreeNode("B", TreeNode("A"), D)
I = TreeNode("I", TreeNode("H"))
G = TreeNode("G", None, I)
F = TreeNode("F", B, G)
tree.insertNode(F)
print("Breadth First Search...")
breadthFirstSearch(tree.root)
print("Depth First Search...")
depthFirstSearch(tree.root)