Python - Leaf and Non-Leaf Nodes Dictionary

Dictionary is an important data structure in Python which consists of key-value pairs. A nested dictionary can represent tree-like structures with nodes, where some nodes are leaf nodes (terminal nodes with no children) and others are non-leaf nodes (internal nodes with children). In this article, we will explore different approaches to identify and manipulate leaf and non-leaf nodes in Python dictionaries.

What are Leaf and Non-Leaf Nodes?

In tree-like dictionary structures, nodes are categorized based on whether they have children ?

  • Leaf node: A node that does not have any child nodes. These are terminal nodes at the end of branches.

  • Non-leaf node: A node that has one or more child nodes. These are internal nodes that connect to other nodes in the hierarchy.

Method 1: Using Iteration with Children Key

This approach checks for the presence of a "children" key to determine if a node is a leaf or non-leaf node ?

def is_leaf_node(node, tree):
    if node not in tree:
        return False
    return "children" not in tree[node]

def find_leaf_nodes(tree):
    leaf_nodes = []
    for node in tree:
        if is_leaf_node(node, tree):
            leaf_nodes.append(node)
    return leaf_nodes

def find_non_leaf_nodes(tree):
    non_leaf_nodes = []
    for node in tree:
        if not is_leaf_node(node, tree):
            non_leaf_nodes.append(node)
    return non_leaf_nodes

tree = {
    "A": {"value": 1},
    "B": {"value": 2},
    "C": {"value": 3},
    "X": {"value": None, "children": ["A", "B"]},
    "Y": {"value": None, "children": ["C"]}
}

leaf_nodes = find_leaf_nodes(tree)
print("Leaf nodes:", leaf_nodes)

non_leaf_nodes = find_non_leaf_nodes(tree)
print("Non-leaf nodes:", non_leaf_nodes)
Leaf nodes: ['A', 'B', 'C']
Non-leaf nodes: ['X', 'Y']

Method 2: Using List Comprehension

List comprehension provides a more concise way to filter nodes. This example uses an explicit "is_leaf" flag in the dictionary ?

def find_leaf_nodes(tree):
    return [node for node, data in tree.items() if data.get("is_leaf")]

def find_non_leaf_nodes(tree):
    return [node for node, data in tree.items() if "children" in data]

tree = {
    "A": {"value": 1, "is_leaf": True},
    "B": {"value": 2, "is_leaf": True},
    "C": {"value": 3, "is_leaf": True},
    "X": {"value": None, "children": ["A", "B"]},
    "Y": {"value": None, "children": ["C"]}
}

leaf_nodes = find_leaf_nodes(tree)
print("Leaf nodes:", leaf_nodes)

non_leaf_nodes = find_non_leaf_nodes(tree)
print("Non-leaf nodes:", non_leaf_nodes)
Leaf nodes: ['A', 'B', 'C']
Non-leaf nodes: ['X', 'Y']

Method 3: Using Parent-Child Relationships

When the dictionary represents direct parent-child relationships, you can identify leaf nodes as those that don't appear as values (parents) of other nodes ?

def find_leaf_nodes(tree):
    # Nodes that are not parents (don't appear as values)
    all_parents = set(tree.values())
    all_parents.discard(None)  # Remove None values
    return [node for node in tree.keys() if node not in all_parents]

def find_non_leaf_nodes(tree):
    # Nodes that are parents (appear as values)
    all_parents = set(tree.values())
    all_parents.discard(None)  # Remove None values
    return [node for node in tree.keys() if node in all_parents]

tree = {
    "A": None,      # A is a leaf (no parent)
    "B": "X",       # B's parent is X
    "C": "Y",       # C's parent is Y
    "X": "root",    # X's parent is root
    "Y": "root"     # Y's parent is root
}

leaf_nodes = find_leaf_nodes(tree)
print("Leaf nodes:", leaf_nodes)

non_leaf_nodes = find_non_leaf_nodes(tree)
print("Non-leaf nodes:", non_leaf_nodes)
Leaf nodes: ['A']
Non-leaf nodes: ['X', 'Y', 'root']

Comparison

Method Best For Requirements
Children Key Check Explicit tree structures Dictionary with "children" key
List Comprehension Compact, readable code Pre-marked leaf flags or children keys
Parent-Child Values Simple hierarchical data Parent stored as value

Conclusion

The choice of method depends on your dictionary structure. Use the children key approach for explicit tree structures, list comprehension for concise code, and parent-child relationships for simple hierarchical data. Each method offers different advantages based on your specific use case.

Updated on: 2026-03-27T08:35:18+05:30

610 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements