Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Traverse tree to collect all children nodes, excluding unrelated branches

I have a list of child-parent tuples. I would like to traverse through the tree to collect all the children for input node.

in_list = [(2,1),(3,2),(4,3),(6,5),(7,4),(8,4)]

Say now I would like to collect all children for node 2. That would be

out_list = [3,4,7,8]

Does this problem or its solution have any specific name? Just need to know where to look.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You need to traverse these nodes in in_list like DFS, You can try this:

def DFS(path, lst, father):
    for (a,b) in lst:
        if b == father:
            path.append(a)
            DFS(path, lst, a)
    return path

in_list = [(2,1),(3,2),(4,3),(6,5),(7,4),(8,4)]
res = DFS([], in_list , 2)
print(res)

Output:

[3, 4, 7, 8]
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading