kayjan / bigtree

Tree Implementation and Methods for Python, integrated with list, dictionary, pandas and polars DataFrame.

Home Page:https://bigtree.readthedocs.io

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

How to extract a subtree given the root node for the subtree and depth from that root node

RomStriker opened this issue · comments

Hi,

I have a large tree and I would like to extract a part of that tree. I have the name of the node that I would like to be the root node in my new tree and the max depth of the new tree. How can I do this? Thanks.

Hi, you can find the node that you want to make as the new root through find_name (or any other tree search method) and assign the node’s parent as None, that will single out / extract out the sub-tree as a tree by itself. Hope this answers your question!

That works, thanks. For cutting off the sub-tree after certain depth you can use something like below.

for i, level in enumerate(levelordergroup_iter(root)):
        # remove all nodes after max_depth
        if i == max_depth:
            for node in level:
                shift_nodes(root, [node.path_name], [None])

Thanks for the follow up, perhaps I can extend the pruning function or create another pruning function for this, good idea!