File tree 1 file changed +47
-0
lines changed
1 file changed +47
-0
lines changed Original file line number Diff line number Diff line change
1
+ class Node :
2
+ def __init__ (self , value ) -> None :
3
+ self .value = value
4
+ self .left = None
5
+ self .right = None
6
+
7
+
8
+ def breadth_first_search (root ) -> None :
9
+
10
+ if root is None :
11
+ print ("# No output as the tree is empty." )
12
+ return
13
+
14
+ queue = []
15
+ queue .append (root )
16
+ result = []
17
+
18
+ while queue :
19
+ current_node = queue .pop (0 )
20
+ result .append (current_node .value )
21
+ print (current_node .value , end = " " )
22
+
23
+ if current_node .left :
24
+ queue .append (current_node .left )
25
+ if current_node .right :
26
+ queue .append (current_node .right )
27
+
28
+ print ("Breadth-First Search traversal:" )
29
+ print (" " .join (map (str , result )))
30
+
31
+
32
+ if __name__ == "__main__" :
33
+ # Constructing the search tree
34
+ root = Node (1 )
35
+ root .left = Node (2 )
36
+ root .right = Node (3 )
37
+ root .left .left = Node (4 )
38
+ root .left .right = Node (5 )
39
+ root .right .left = Node (6 )
40
+ root .right .right = Node (7 )
41
+
42
+ # Running the breadth-first search
43
+ breadth_first_search (root )
44
+
45
+ # Test with an empty tree
46
+ root = None
47
+ breadth_first_search (root )
You can’t perform that action at this time.
0 commit comments