How to Remove a Node and Get It Back in treelib: A Complete Guide
Use Tree.remove_subtree() to detach a node and its descendants as a separate Tree object, then reattach it later using Tree.paste() or Tree.merge_tree().
The treelib library provides flexible tree manipulation utilities that allow you to temporarily remove nodes and restore them later without losing data. Whether you need to prune branches for analysis or rearrange your tree structure, understanding how to remove a node and get it back in treelib is essential for effective tree management in the caesar0301/treelib repository.
Detaching Nodes with remove_subtree()
The primary method for removing a node while preserving its structure is Tree.remove_subtree(), implemented in treelib/tree.py at line 1629. This method detaches the specified node and all its descendants from the original tree and returns them as a new Tree instance.
When you call remove_subtree(), the original tree loses the node and its children, but the data remains intact in the returned subtree object. This makes it ideal for temporary removal scenarios where you intend to restore the branch later.
from treelib import Tree
# Build a sample tree
tree = Tree()
tree.create_node("Root", "root")
tree.create_node("Branch A", "a", parent="root")
tree.create_node("Branch B", "b", parent="root")
tree.create_node("Leaf C", "c", parent="a")
tree.create_node("Leaf D", "d", parent="a")
# Detach node "a" and its children
subtree = tree.remove_subtree("a")
Reattaching Subtrees Using paste() and merge_tree()
Once you have detached a subtree using remove_subtree(), you can reattach it to any location in your original tree or to a different tree entirely. The treelib library provides two primary methods for this operation, both located in treelib/tree.py.
Using Tree.paste()
The paste() method (line 1534) attaches an entire subtree under a specified parent node. By default, it moves the reference, meaning the original subtree object becomes empty after pasting. Set deep=True to create a copy instead, preserving the original subtree object.
# Reattach the previously removed subtree under node "b"
tree.paste("b", subtree, deep=False)
Using Tree.merge_tree()
The merge_tree() method (line 1519) functions similarly but adds the root of the subtree as a child of the given node. This is useful when you want to integrate the subtree structure while maintaining the hierarchical relationship.
# Merge subtree under node "root"
tree.merge_tree("root", subtree, deep=False)
Deep Copy vs Reference
Both paste() and merge_tree() accept a deep parameter:
deep=False(default): Moves the nodes by reference. The source subtree becomes empty after the operation.deep=True: Creates a deep copy of all nodes. The original subtree remains intact, allowing you to paste it multiple times.
Preserving Individual Nodes with remove_node()
If you need to remove only a single node without the automatic subtree packaging, use Tree.remove_node() (line 1602). This method returns the number of removed nodes rather than the node data itself, so you must save a reference to the node before removal if you intend to restore it later.
# Save the node object before removal (including its data)
saved_node = tree["node_id"]
# Remove the node (and its children) from the tree
removed_count = tree.remove_node("node_id")
# Later, re-insert the saved node under a new parent
tree.add_node(saved_node, parent="new_parent_id")
This approach differs from remove_subtree() in that it does not automatically package the node and its descendants into a new Tree object. It is best suited for scenarios where you are managing node objects manually or only need to relocate specific nodes without their subtrees.
Key Differences Between remove_subtree and remove_node
Understanding when to use each removal method ensures you maintain data integrity while manipulating tree structures.
| Operation | Returns | Use Case |
|---|---|---|
remove_subtree(id) |
Tree object containing the removed node and all descendants |
When you need to detach and restore a branch later, or move it between trees. |
remove_node(id) |
int – count of deleted nodes |
When you only care about deletion counts and do not need the node data back, or when you manually saved a reference beforehand. |
The remove_subtree() method is the preferred approach for "remove and get it back" workflows because it encapsulates the entire branch structure, preserving parent-child relationships and node data in a reusable Tree instance.
Summary
- Use
Tree.remove_subtree()(implemented intreelib/tree.pyat line 1629) to detach a node and its descendants as a separateTreeobject that can be reattached later. - Reattach detached subtrees using
Tree.paste()(line 1534) orTree.merge_tree()(line 1519), choosingdeep=Trueto create copies ordeep=Falseto move by reference. - For single node removal without automatic subtree packaging, use
Tree.remove_node()(line 1602), but manually save a reference to the node before removal if you need to restore it. - The
remove_subtree()method is the robust solution for temporarily removing branches while preserving their structure for later restoration incaesar0301/treelib.
Frequently Asked Questions
How do I remove a node without deleting its children in treelib?
To remove a node while preserving its children, you must first move the children to a new parent or save them separately before calling remove_node(). The library does not provide a direct "remove parent but keep children" method because the tree structure requires every node (except root) to have a parent. You can iterate through the children using tree.children(node_id) and reparent them before removal.
Can I move a node to a different parent in treelib?
Yes, you can move a node to a different parent by first detaching it with remove_subtree() and then reattaching it with paste() or merge_tree() under the new parent ID. This preserves the node and all its descendants. Alternatively, you can manually update the _parent attribute of the node and update the tree's internal dictionaries, but using the official API methods ensures data consistency.
What is the difference between paste() and merge_tree() in treelib?
Both methods attach a detached subtree to a parent node, but they differ in how they handle the subtree root. paste() (line 1534) attaches the entire subtree under the specified parent, making the subtree's root a child of the target parent. merge_tree() (line 1519) also adds the subtree root as a child but is specifically designed for merging tree structures and handles the integration slightly differently in terms of internal node registration. In practice, paste() is more commonly used for moving branches, while merge_tree() is useful for combining separate tree instances.
How do I preserve node data when removing and reinserting a node?
To preserve node data, use remove_subtree() which returns a Tree object containing all node objects with their data intact, or manually save a reference to the node with saved_node = tree[node_id] before calling remove_node(). When using remove_subtree(), the node objects maintain their data attributes, tags, and other properties. When reinserting with paste() or add_node(), these properties remain attached to the node object.
Have a question about this repo?
These articles cover the highlights, but your codebase questions are specific. Give your agent direct access to the source. Share this with your agent to get started:
curl -s "https://instagit.com/install.md" Maintain an open-source project? Get it listed too →