Tree with no duplicate children

2020-07-17 04:58发布

问题:

Using anytree I produced such tree:

A
├── B
│   └── C
│       └── D
│           └── F
└── B
    └── C
        └── E
            └── G

Is there a way to remove all duplicate children and turn it into the tree below (recursive for children at all possible levels)?

A
└── B
    └── C
        ├── D
        |   └── F
        └── E
            └── G

Edit:

What I am trying to achieve is a tree of all links on a website. So everything between slashes would become a child: .../child/... (second slash is optional). The above is just a representation of my problem, but I hope it's clear.

Here is my Node generation:

root = Node('A')
for link in links:
    children = link.split('/')
    cur_root = Node(children[0], parent=root)
    for one in children[1:]:
        cur_root = Node(one, parent=cur_root)

回答1:

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).