caesar0301/treelib

Swap the root of the tree!

NikosDelijohn opened this issue · 0 comments

Good evening everyone. I would like some assistance on a specific matter of treelib's tree.

Lets assume that I am having the following code:

from treelib import Tree,Node
tree = Tree()
tree.create_node(tag=0,identifier=0) # ROOT
tree.create_node(tag=1,identifier=1,parent=0) # 1st Child
tree.create_node(tag=2,identifier=2,parent=0) # 2nd Child
tree.create_node(tag=3,identifier=3,parent=0) # 3rd Child

new_root = Node(tag=0,identifier=4)

I wish to swap the tree.root with the new_root Node but I am stuck. Is there a function that I am missing that may be of help to me? Or any suggestions? Thank you in advance

def SwapRoots(tree,new_root):

  n_subtrees = list()

  new_tree = Tree()

  new_tree.add_node(new_root)

  for child in tree.children(tree.root):
    
    n_subtrees.append(tree.subtree(child.identifier))

  for subtree in n_subtrees:
    subtree.show()
    new_tree.paste(new_root.identifier,subtree)

  new_tree.show() 
  return new_tree

Ι have written the aforementioned piece of code but is there a more efficient way to do it?