create cached tree generator in python

To create a cached tree generator in Python, we can use memoization to cache and reuse the result of recursive calls. Here's an implementation that generates a binary tree of a given size:

main.py
from functools import lru_cache

@lru_cache(maxsize=None)
def generate_tree(size):
    if size == 0:
        return None
    if size == 1:
        value = input("Enter value for tree node: ")
        return Node(value)
    result = []
    for left_size in range(size):
        right_size = size - left_size - 1
        for left in generate_tree(left_size):
            for right in generate_tree(right_size):
                node = Node("X", left, right)
                result.append(node)
    return result
509 chars
18 lines

This function uses the lru_cache decorator from the functools module to cache the result of each call based on its arguments. When called with a given size, it first checks if the result has already been cached, and returns that if available. Otherwise, it generates all possible left and right subtrees of the desired size recursively, and combines them with a new node to form the final tree. This result is then cached and returned.

Note that this implementation assumes the Node class has a constructor that takes a value (for the root node) and optional left and right children, and that input is used to get user input for each leaf node. You can modify these parts to suit your needs.

gistlibby LogSnag