-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Data Structures - Trees
- Loading branch information
Showing
1 changed file
with
23 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,23 @@ | ||
class TreeNode: | ||
def __init__(self, value): | ||
self.value = value # data | ||
self.children = [] # references to other nodes | ||
|
||
def add_child(self, child_node): | ||
# creates parent-child relationship | ||
print("Adding " + child_node.value) | ||
self.children.append(child_node) | ||
|
||
def remove_child(self, child_node): | ||
# removes parent-child relationship | ||
print("Removing " + child_node.value + " from " + self.value) | ||
self.children = [child for child in self.children | ||
if child is not child_node] | ||
|
||
def traverse(self): | ||
# moves through each node referenced from self downwards | ||
nodes_to_visit = [self] | ||
while len(nodes_to_visit) > 0: | ||
current_node = nodes_to_visit.pop() | ||
print(current_node.value) | ||
nodes_to_visit += current_node.children |