How to Get Direct Children of a Node in treelib: Complete Guide

Call Tree.children(nid) on your Tree instance to retrieve a Python list of Node objects representing the immediate children of the specified identifier.

Working with hierarchical data in Python requires efficient traversal of parent-child relationships. In treelib—a lightweight, pure-Python library for managing tree data structures—accessing the direct descendants of any node is a core operation handled by a single public method. This guide explains how to get direct children of a node in treelib using both the public API and the underlying implementation details from the caesar0301/treelib source code.

Using Tree.children() to Get Direct Children

The primary entry point for retrieving immediate descendants is the Tree.children(nid) method, where nid is the unique string identifier of the parent node.

This method performs three critical operations internally:

  1. Validates that the provided identifier exists in the tree's internal storage
  2. Fetches the list of child identifiers via the is_branch() helper
  3. Materializes full Node objects from the identifier list

If the specified nid does not exist in the tree, the method raises NodeIDAbsentError. Otherwise, it returns a Python list of Node instances in their original insertion order.

Internal Implementation Details

According to the source code in treelib/tree.py, the children() implementation (lines 558‑592) relies on the tree's internal dictionary architecture (self._nodes) to resolve relationships.

Identifier Validation

The method first verifies that nid exists within self._nodes. If the identifier is absent, the method raises NodeIDAbsentError immediately.

Fetching Child Identifiers via is_branch()

The method delegates to self.is_branch(nid) (defined at lines 1525‑1552 in treelib/tree.py), which returns a list of child identifiers by reading the parent node's successor list: self[nid].successors(self._identifier). At this stage, the result contains only string identifiers, not object instances.

Materializing Node Objects

Finally, children() constructs the return value using a list comprehension that maps identifiers to objects: [self[i] for i in self.is_branch(nid)]. The __getitem__ overload performs the dictionary lookup in self._nodes to retrieve each corresponding Node instance defined in treelib/node.py.

Practical Code Examples

Here are complete, runnable examples demonstrating how to retrieve direct children in various scenarios:

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")

# Example 1: Get direct children of the root node

root_children = tree.children("company")
print([node.tag for node in root_children])

# Output: ['Engineering', 'Sales']

# Example 2: Iterate over direct children of a specific node

for child in tree.children("eng"):
    print(f"Team member: {child.tag}")

# Output:

# Team member: Alice

# Team member: Bob

# Example 3: Count direct children (depth = 1 only)

sales_count = len(tree.children("sales"))
print(f"Direct reports in Sales: {sales_count}")

# Output: Direct reports in Sales: 1

Working with Return Values

Node Objects vs. Identifiers

The children() method returns full Node objects containing the tag, identifier, data payload, and parent pointer. If you require only the raw identifier strings (for memory efficiency or further key-based lookups), use tree.is_branch(nid) directly instead.

Insertion Order Preservation

The list returned by children() maintains the insertion order of nodes as they were added to the parent. This order remains stable unless you explicitly invoke sorting methods on the Tree instance.

Summary

  • Use Tree.children(nid) to get direct children of a node in treelib as a list of Node objects.
  • The method validates identifiers against self._nodes and raises NodeIDAbsentError for invalid inputs.
  • Internally, children() relies on is_branch() (lines 1525‑1552) to resolve identifiers and __getitem__ to materialize objects (lines 558‑592 of treelib/tree.py).
  • The operation returns only immediate children (depth = 1), not grandchildren or deeper descendants.
  • For raw identifier strings, call is_branch() directly; for full objects, use children().

Frequently Asked Questions

What is the difference between children() and is_branch() in treelib?

is_branch() returns a list of string identifiers representing direct children, while children() returns a list of instantiated Node objects. According to the implementation in treelib/tree.py, children() is essentially a convenience wrapper that calls is_branch() to get identifiers, then maps each ID to its corresponding Node via the internal self._nodes dictionary.

Does children() return grandchildren or only direct children?

children() returns only direct children. It queries the immediate successor list of the specified node and does not recurse deeper into the tree. To access grandchildren or all descendants, you must implement recursive traversal or use tree.expand_tree() with appropriate depth controls.

What happens if I call children() on a leaf node?

Calling children() on a leaf node returns an empty Python list []. The method does not raise an exception; it simply indicates that the node's successor list contains no identifiers. You can safely use this return value in boolean checks like if tree.children(nid): to detect leaf nodes.

How do I get child identifiers instead of full Node objects?

To retrieve only the string identifiers without instantiating Node objects, call tree.is_branch(nid) directly. This method returns the raw list of child IDs as stored in the parent's successor list (accessed via self[nid].successors(self._identifier)), which is more memory-efficient when you do not need the full node metadata.

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:

Share the following with your agent to get started:
curl -s "https://instagit.com/install.md"

Works with
Claude Codex Cursor VS Code OpenClaw Any MCP Client

Maintain an open-source project? Get it listed too →