File tree Expand file tree Collapse file tree 1 file changed +41
-0
lines changed Expand file tree Collapse file tree 1 file changed +41
-0
lines changed Original file line number Diff line number Diff line change
1
+ class Node :
2
+ def __init__ (self , val = None , left = None , right = None ):
3
+ self .val = val
4
+ self .left = left
5
+ self .right = right
6
+
7
+ def __str__ (self ):
8
+ return f"Node:{ self .val } "
9
+
10
+ __repr__ = __str__
11
+
12
+
13
+ class Tree :
14
+ def __init__ (self , root ):
15
+ self .root = root
16
+
17
+ @classmethod
18
+ def build_tree_from_array (cls , array ):
19
+ # array BFS
20
+
21
+ lens = len (array )
22
+ node_list = [Node (val ) for val in array ]
23
+ t = cls (node_list [0 ])
24
+ for idx , node in enumerate (node_list ):
25
+ left_idx = 2 * idx + 1
26
+ right_idx = 2 * idx + 2
27
+ if left_idx < lens :
28
+ node .left = node_list [left_idx ]
29
+ if right_idx < lens :
30
+ node .right = node_list [right_idx ]
31
+ return t
32
+
33
+ def bfs (self ):
34
+ queue = [self .root ]
35
+ res = []
36
+ while queue :
37
+ cur = queue .pop (0 )
38
+ res .append (cur .val )
39
+ cur .left and queue .append (cur .left )
40
+ cur .right and queue .append (cur .right )
41
+ return res
You can’t perform that action at this time.
0 commit comments