Dynamically set Node, Python3 - BinaryTree module

36 Views Asked by At

I was experimenting with graphs in python and i felt into a problem.

Here is the code :

class IspNetwork :
    def __init__(self) -> None:
        self.root : Node = Node("isp")

    def add_node(self, obj) :
        node = ObjectEncoder().encode(obj)
        self.root.left = Node(node)
        pass

The output is as expected, one root node and a node on the left branch.

Now my question is, how to dynamically set multiple nodes on the left branch, it should be something like : self.left.left...left.left = Node(node)

But I cant figure out how to do it the right way.

I tried to use __setattr__(), some gibberish like self.left. + 3*"left" = Node(node).

But none of those worked so any help would be highly appreciated !

1

There are 1 best solutions below

0
kiraoverflow On

To add a branch to a specific node we can set the index of the node we want to expand.

class IspNetwork :
    def __init__(self) -> None:
        self.root : Node = Node("isp")

    def add_node(self, index, obj) :
        self.root[index].__setattr__("left", Node(obj))

Thank's to @trincot for helping me solve the issue !