Skip to content

Commit 2009de1

Browse files
committed
add tree
1 parent b5c4d18 commit 2009de1

File tree

1 file changed

+41
-0
lines changed

1 file changed

+41
-0
lines changed

ehco/tree/tree.py

Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
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

0 commit comments

Comments
 (0)