mjschultz / py-radix

Python radix tree implementation for IPv4 and IPv6 prefix matching.
Other
119 stars 37 forks source link

How to get all leaf nodes in radix tree #46

Open RSwarnkar opened 4 years ago

RSwarnkar commented 4 years ago

How to get all leaf nodes from radix tree?

ljluestc commented 1 month ago
import radix

# Function to check if a node is a leaf node
def is_leaf(node):
    return not node.prefixes()

# Function to collect all leaf nodes
def get_all_leaf_nodes(rt):
    leaf_nodes = []
    for node in rt:
        if is_leaf(node):
            leaf_nodes.append(node)
    return leaf_nodes

# Example usage
def main():
    rt = radix.Radix()

    # Adding some prefixes
    rt.add("1.2.2.0/23")
    rt.add("1.2.2.0/24")
    rt.add("1.2.3.0/24")
    rt.add("1.2.4.0/24")

    # Getting all leaf nodes
    leaf_nodes = get_all_leaf_nodes(rt)

    # Printing all leaf nodes
    for leaf in leaf_nodes:
        print(leaf.prefix)

if __name__ == "__main__":
    main()