Home > Back-end >  How to find a list of lists of all possible paths in a tree
How to find a list of lists of all possible paths in a tree

Time:07-04

I need to find a list of lists when traversing through a list of objects in python and need to create every possible path

The output should look something like this

[[24,137,237], [24,137,251], [24,151,155], [24,151,155,154]]

The input looks like this:

    {
        "id": 24,
        "children": [
            {
                "id": 137,
                "children": [
                    {
                        "id": 237,
                        "children": [],
                    },
                    {
                        "id": 251,
                        "children": [],
                    }
                ],
            },
            {
                "id": 151,
                "children": [
                    {
                        "id": 155,
                        "children": [],
                    },
                    {
                        "id": 154,
                        "children": [],
                    }
                ],
            },
        ],
    },
]```

Current code does something similar but not quite the desired result.
```python
            def create_category_paths_from_children(
                children: List[CategoriesTreeNodeFull], category_paths_list: List[CategoryPath]
        ) -> List[CategoryPath]:

            for child in children:
                category_paths_list.append(CategoryPath(name=child.name, id=child.id))
                if len(child.children) > 0:
                    create_category_paths_from_children(child.children, category_paths_list)

            return category_paths_list```
Edit: updated my current code.

CodePudding user response:

Here's the solution I came up with:

def getAllPaths(tree, upto = [], current_trees = []):
    upto = upto   [tree.id]
    if len(tree.children) == 0:
        current_trees.append(upto)
    else:
        for branch in tree.children:
            getAllPaths(branch, upto, current_trees)
    return current_trees

This is assuming the "object" you described looks something like the following in python code:

class Tree:
    id = 0           # Some int
    children = []    # Some list of Tree objects
  • Related