Tree with no duplicate children

谁说我不能喝 提交于 2019-12-04 14:08:37
Willem Van Onsem

The problem is that each time you add a new link, you add a new sequence of nodes from the root to the last child. But it is definitely possible (and plausible) that you already partially added such a path.

A quick fix can be to simply check if a child is already added to the node, and only if not add it to the node. Like:

root = Node('A')
for link in links:
    node = root
    for child in link.split('/'):
        sub = next((c for c in node.children if c.name == child),None)
        if sub is None:
            sub = Node(child,parent=node)
        node = sub

So for each link in links, we set node initially to root. Then for each child we will first search the node for a child with the same name. If we can find such a child (sub is not None), we construct a new child. Regardless whether the node was already a child, we move to the child until the end of the link.

This will ensure that there are no (partially) duplicated paths in the tree and furthermore it will reduce the amount of memory it uses since less objects will be constructed (and thus less objects are stored in memory).

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!