Created
August 11, 2022 02:44
-
-
Save ckahle33/51e0e03797f503063c8ec855bd46adbb to your computer and use it in GitHub Desktop.
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
class Tree: | |
def __init__(self): | |
self.nodes = [] | |
self.root = None | |
def add_node(self, node=None): | |
if node: | |
self.nodes.append(node) | |
def list_nodes(self): | |
# need to recurse here... | |
for n in self.nodes: | |
print("parent -- ", n.parent) | |
print("name", n.name) | |
if len(n.children): | |
for c in n.children: | |
c.list_children() | |
print("children", c.name) | |
print('-----------------------') | |
class Node: | |
def __init__(self, name=None, parent=None): | |
self.name = name | |
self.parent = parent | |
self.children = [] | |
def add_node(self, node=None): | |
if node: | |
self.children.append(node) | |
def list_children(self): | |
for c in self.children: | |
print(c.name) | |
def get_level(self): | |
return | |
class Solution: | |
tree = Tree() | |
def __init__(self): | |
return | |
def build_tree(self, arr): | |
for a in arr: | |
n = Node(name=a[1], parent=a[0]) | |
self.tree.add_node(n) | |
self.balance(n) | |
print(self.tree.list_nodes()) | |
def balance(self, node): | |
for n in self.tree.nodes: | |
if n.parent == node.name: | |
self.tree.nodes.remove(n) | |
node.add_node(n) | |
self.balance(node) | |
a = Solution() | |
a.build_tree([ | |
["dog", "poodle"], | |
["dog", "pomeranian"], | |
["canine", "dog"], | |
["canine", "wolf"], | |
["feline", "cat"], | |
["cat", "persian"], | |
["mammal", "feline"], | |
["mammal", "canine"], | |
["reptile", "crocodile"], | |
["feline", "jaguar"], | |
["reptile", "iguana"], | |
["feline", "lion"], | |
["mammal", "monotreme"], | |
["dog", "st bernard"], | |
["reptile", "turtle"] | |
] | |
) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment