Created
May 14, 2021 02:22
-
-
Save magiskboy/d71d2d88b00b0f8c11ee3158958337ca 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 Node: | |
def __init__(self, key, data): | |
self.key = key | |
self.data = data | |
self.children = [] | |
def display(self, level=0): | |
tab = " " * (level * 3) | |
print(tab + self.data) | |
for child in self.children: | |
child.display(level + 1) | |
paths = [ | |
{"key": 2, "data": "book", "path": "store/book", "parent_key": 1}, | |
{"key": 4, "data": "science", "path": "store/book/science", "parent_key": 2}, | |
{"key": 3, "data": "novel", "path": "store/book/novel", "parent_key": 2}, | |
{"key": 6, "data": "macbook", "path": "store/computer/macbook", "parent_key": 5}, | |
{"key": 1, "data": "store", "path": "store", "parent_key": None}, | |
{"key": 5, "data": "computer", "path": "store/computer", "parent_key": 1}, | |
{"key": 7, "data": "dell", "path": "store/computer/dell", "parent_key": 5}, | |
] | |
def build_tree(flat): | |
tree = {} | |
flat.sort(key=lambda x: x["path"]) | |
visited = {} | |
for item in flat: | |
key = item["key"] | |
node = Node(key, item["data"]) | |
visited[key] = node | |
parent_key = item["parent_key"] | |
if parent_key not in visited: | |
tree = node | |
else: | |
parent = visited[parent_key] | |
parent.children.append(node) | |
return tree | |
tree = build_tree(paths) | |
tree.display() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment