Last active
December 27, 2018 07:30
-
-
Save xcaptain/ff7816e06cdd0de4cae30d49316c3cf4 to your computer and use it in GitHub Desktop.
a generic tree in python
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
# generic tree in python | |
# to demostrate a category tree | |
class Tree: | |
def __init__(self): | |
self.roots = [] | |
def add_root(self, val): | |
node = Node(val) | |
self.roots.append(node) | |
return node | |
def add_child(self, parent, val): | |
return parent.add_child(val) | |
def get_children(self, parent): | |
# get all the children in a parent | |
for child in parent.children: | |
print("child:", child.value) | |
class Node: | |
def __init__(self, val): | |
self.children = [] | |
self.value = val | |
def add_child(self, val): | |
n = Node(val) | |
self.children.append(n) | |
return n | |
t = Tree() | |
n1 = t.add_root(1) | |
n2 = t.add_root(2) | |
n11 = n1.add_child(11) | |
n12 = n1.add_child(12) | |
n13 = t.add_child(n1, 13) | |
n2.add_child(21) | |
print("children of node:1") | |
t.get_children(n1) | |
print("children of node:2") | |
t.get_children(n2) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment