How to Display a Specific Subtree in treelib: Complete Guide
Use Tree.show(nid="node_id") for instant visualization or Tree.subtree("node_id") to create an independent copy that you can display, export, or modify without affecting the original tree.
The treelib library provides pure Python implementations of tree data structures for managing hierarchical relationships. When analyzing large hierarchies in the caesar0301/treelib repository, you often need to isolate specific branches without rendering the entire structure. The Tree class in treelib/tree.py offers two distinct APIs for displaying and extracting subtrees rooted at any node identifier.
Display a Subtree Directly with Tree.show()
The simplest way to display a specific subtree is passing the node identifier (nid) to the show() method. This instructs the printer to start traversal from that specific node, rendering only its descendants while hiding the rest of the hierarchy.
According to the source code in treelib/tree.py (lines 1731–1744), the show() method forwards your nid argument to the internal __print_backend, which builds the visual representation starting at the specified node. If the identifier does not exist, the method raises NodeIDAbsentError to prevent silent failures.
from treelib import Tree
# Build a sample organizational tree
tree = Tree()
tree.create_node("Company", "company") # root
tree.create_node("Engineering", "eng", parent="company")
tree.create_node("Sales", "sales", parent="company")
tree.create_node("Alice", "alice", parent="eng")
tree.create_node("Bob", "bob", parent="eng")
tree.create_node("Carol", "carol", parent="sales")
# Display only the Engineering subtree
tree.show(nid="eng")
# Output:
# Engineering
# ├── Alice
# └── Bob
Extract and Display an Independent Subtree with Tree.subtree()
When you need a separate Tree object that you can manipulate, export, or display repeatedly without affecting the original structure, use the subtree() method. This creates a shallow copy of the tree rooted at the specified node.
As implemented in treelib/tree.py (lines 1883–1909), subtree() first creates an empty clone via self._clone(). It then copies every node reachable from the target nid using expand_tree and rewires their parent/child pointers so the copied node becomes the new root. The original tree remains unchanged because the method preserves original node objects while creating new container relationships.
# Extract the Sales branch as a new Tree instance
sales_sub = tree.subtree("sales")
# The copy operates independently - add nodes without affecting the original
sales_sub.create_node("Dave", "dave", parent="sales")
sales_sub.show()
# Output:
# Sales
# ├── Carol
# └── Dave
You can then export this independent branch using built-in serialization methods:
import json
# Convert the subtree to a dictionary for JSON export
sales_json = sales_sub.to_dict()
print(json.dumps(sales_json, indent=2))
Comparing show() vs. subtree()
Understanding when to use each method ensures efficient memory usage and clean code architecture:
Tree.show(nid=...)– Best for quick debugging or console output when you do not need to preserve the subset. This operates on the original tree structure and returnsNone, printing directly to stdout.Tree.subtree(nid=...)– Required when you need to pass the subset to other functions, export data formats, or modify the branch independently. This returns a newTreeinstance containing shallow copies of the relevant nodes.
Both methods validate the node identifier and raise NodeIDAbsentError if the nid is not found in the tree, ensuring safe traversal operations.
Summary
- Use
Tree.show(nid="node_id")for immediate console visualization of any branch without creating new objects. - Use
Tree.subtree("node_id")to generate an independentTreeinstance that you can modify, export, or display separately from the parent hierarchy. - Both methods are implemented in
treelib/tree.pyand preserve original node objects while providing safe error handling viaNodeIDAbsentError. - The
subtree()method performs shallow cloning via_clone()andexpand_treeto rewire parent/child pointers efficiently.
Frequently Asked Questions
What happens if I pass a non-existent node ID to show() or subtree()?
Both methods raise a NodeIDAbsentError exception immediately. According to the implementation in treelib/tree.py, the validation occurs before any printing or cloning begins, preventing operations on invalid node references.
Does subtree() modify the original tree?
No. The subtree() method creates a shallow copy of the tree structure using self._clone() and only references the original node objects without altering their relationships in the source tree. You can safely add or remove nodes from the returned subtree without affecting the original hierarchy.
Can I export a subtree to JSON without creating a copy?
While Tree.show() only prints to stdout, you can use Tree.to_dict() with filtering logic on the original tree, but subtree() provides the cleanest API for export operations. The method returns a true Tree object with its own to_dict() method, making JSON serialization straightforward as shown in the examples above.
Is subtree() memory efficient for large trees?
Yes. The implementation uses shallow copying via expand_tree to traverse and clone only the nodes reachable from the specified root. It does not duplicate the entire original tree, making it suitable for extracting branches from large hierarchies without excessive memory overhead.
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 →