# How to Get the Parent of a Node in treelib: Complete Guide with Examples

> Easily get the parent of a node in treelib using the tree.parent(node_id) method. Learn how to retrieve the parent Node object with code examples from the caesar0301/treelib repository.

- Repository: [Xiaming Chen/treelib](https://github.com/caesar0301/treelib)
- Tags: how-to-guide
- Published: 2026-02-26

---

**Use `tree.parent(node_id)` to retrieve the immediate parent `Node` object, which returns `None` if the node is the root or orphaned.**

The treelib library provides an intuitive Python API for managing tree data structures. Whether you are building organizational hierarchies or parsing file systems, accessing parent nodes is a fundamental operation. This guide explains exactly how to retrieve a node's parent using the caesar0301/treelib source code.

## Using the Tree.parent() Method

The primary interface for parent retrieval is the **`Tree.parent()`** method defined in [`treelib/tree.py`](https://github.com/caesar0301/treelib/blob/main/treelib/tree.py).

### Method Signature and Return Value

Call `parent()` with the target node's identifier string:

```python
parent_node = tree.parent(node_id)

```

* **Return type**: A `Node` instance representing the immediate parent, or `None` if the node has no parent (e.g., it is the root).
* **Error handling**: Raises `NodeIDAbsentError` if the provided `node_id` does not exist in the tree.

### Implementation Details

According to the caesar0301/treelib source code, the implementation resides at **line 1448** in [`treelib/tree.py`](https://github.com/caesar0301/treelib/blob/main/treelib/tree.py). The method performs three operations: it validates the node exists, retrieves the predecessor identifier from the node's internal storage, and returns the corresponding `Node` object.

```python
def parent(self, nid: str) -> Optional[Node]:
    if not self.contains(nid):
        raise NodeIDAbsentError("Node '%s' is not in the tree" % nid)
    
    pid = self[nid].predecessor(self._identifier)
    if pid is None or not self.contains(pid):
        return None
    
    return self[pid]

```

The `predecessor()` call accesses the node's parent pointer, which treelib maintains internally as a backward link in the hierarchical structure.

## Practical Code Examples

### Basic Parent Lookup

Create a hierarchy and retrieve a specific parent node:

```python
from treelib import Tree

tree = Tree()
tree.create_node("Company", "company")
tree.create_node("Engineering", "eng", parent="company")
tree.create_node("Alice", "alice", parent="eng")

# Retrieve Alice's parent (Engineering)

parent_node = tree.parent("alice")
print(parent_node.tag)          # → Engineering

print(parent_node.identifier)  # → eng

```

### Handling Root Nodes and Errors

Always check for `None` when dealing with root nodes, and handle missing identifiers safely:

```python
from treelib import Tree, NodeIDAbsentError

tree = Tree()
tree.create_node("Root", "root")

# Root has no parent

parent = tree.parent("root")
if parent is None:
    print("Node is the root")

# Handle non-existent nodes

try:
    tree.parent("invalid_id")
except NodeIDAbsentError as exc:
    print(exc)  # → Node 'invalid_id' is not in the tree

```

### Traversing Upward to the Root

You can chain `parent()` calls to walk from any node up to the root, as demonstrated in [`examples/getting_started.py`](https://github.com/caesar0301/treelib/blob/main/examples/getting_started.py) (lines 115-119):

```python
def path_to_root(tree, start_id):
    path = []
    current_id = start_id
    
    while True:
        parent = tree.parent(current_id)
        if parent is None:
            break
        path.append(parent.tag)
        current_id = parent.identifier
    
    return list(reversed(path))

# Usage

tree = Tree()
tree.create_node("World", "world")
tree.create_node("Continent", "cont", parent="world")
tree.create_node("Country", "coun", parent="cont")
tree.create_node("City", "city", parent="coun")

print(path_to_root(tree, "city"))  # → ['World', 'Continent', 'Country']

```

## Summary

* Call **`tree.parent(node_id)`** to get the parent `Node` in treelib.
* The method returns **`None`** for root nodes and raises **`NodeIDAbsentError`** for invalid identifiers.
* The implementation in [`treelib/tree.py`](https://github.com/caesar0301/treelib/blob/main/treelib/tree.py) (line 1448) uses internal predecessor pointers for O(1) lookups.
* Always guard against `None` returns when traversing upward to avoid attribute errors.

## Frequently Asked Questions

### What does tree.parent() return if the node is the root?

The `tree.parent()` method returns `None` when the specified node has no parent. This occurs when the node is the root of the tree or if the node has been orphaned (its parent was removed while the child remains). Always check the return value before accessing parent attributes like `tag` or `data`.

### How do I check if a node has a parent before calling tree.parent()?

You can call `tree.parent()` directly and check for `None`, or verify the node is not the root by comparing identifiers. Since `tree.parent()` performs a containment check internally, calling it is the most efficient approach. If you need to avoid exceptions for non-existent nodes, wrap the call in a try-except block catching `NodeIDAbsentError`.

### Can I get the parent using the Node object instead of the identifier?

No, the `Tree.parent()` method requires the node's identifier string (`nid`), not the `Node` object itself. If you have a `Node` instance, access its `identifier` attribute first: `tree.parent(node.identifier)`. The `Node` class defined in [`treelib/node.py`](https://github.com/caesar0301/treelib/blob/main/treelib/node.py) stores its identifier but does not maintain a direct reference to its parent object.

### Is there a way to get all ancestors, not just the immediate parent?

treelib does not provide a built-in method for retrieving all ancestors, but you can implement this by recursively or iteratively calling `tree.parent()`. Start with the target node's identifier, call `parent()` in a loop until it returns `None`, and collect the results. This walks the predecessor chain defined in the tree's internal structure until reaching the root.