-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtree.py
More file actions
29 lines (23 loc) · 669 Bytes
/
tree.py
File metadata and controls
29 lines (23 loc) · 669 Bytes
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
class TreeNode:
def __init__(self, data):
self.data = data
self.children = []
self.parent = None
def add_child(self, child):
child.parent = self
self.children.append(child)
def get_level(self):
level = 0
p = self.parent
while p:
level += 1
p = p.parent
return level
def __str__(self):
spaces = " " * self.get_level() * 3
prefix = spaces + "|--" if self.parent else ""
tree = prefix + self.data + "\n"
if self.children:
for child in self.children:
tree += child.__str__()
return tree