Leetcode 1125 Solution

This article provides solution to leetcode question 1125 (design-file-system)

https://leetcode.com/problems/design-file-system

Solution

class FileNode:
    def __init__(self, name, value=None):
        self.name = name
        self.value = value
        self.children = {}

class FileSystem:

    def __init__(self):
        self.root = FileNode(None)

    def createPath(self, path: str, value: int) -> bool:
        node = self.root
        tokens = path[1:].split("/")

        for i, token in enumerate(tokens):
            if i != len(tokens) - 1:
                if token not in node.children:
                    return False
                else:
                    node = node.children[token]
            else:
                if token in node.children:
                    return False
                else:
                    node.children[token] = FileNode(token, value)

        return True

    def get(self, path: str) -> int:
        node = self.root
        tokens = path[1:].split("/")

        for token in tokens:
            node = node.children.get(token)
            if not node:
                return -1

        return node.value if node.value is not None else -1

# Your FileSystem object will be instantiated and called as such:
# obj = FileSystem()
# param_1 = obj.createPath(path,value)
# param_2 = obj.get(path)