Back to Catalog

Implement recursive algorithms with sub-workflows: Towers of Hanoi demo

AdrianAdrian
151 views
2/3/2026
Official Page

How it works

This is an example of using sub-workflow nodes and a proof of concept showing that itโ€™s possible to solve and explain recursive problems with n8n.

Towers of Hanoi - Task

Move a stack of n disks from rod A to rod C, using rod B as auxiliary. Only one disk can be moved at a time, and no disk may be placed on a smaller disk.

Example

n=4
     |          |          |
     =          |          |
    ===         |          |
   =====        |          |
  =======       |          |
 ---------  ---------  ---------
     A          B          C

Algorithm

procedure Hanoi(n, X, Y, Z):
  if n == 1:
    move disk from X to Z
  else:
    Hanoi(n-1, X, Z, Y)
    move disk from X to Z
    Hanoi(n-1, Y, X, Z)

Notes

  • This is a learning example. In a real scenario, you would probably use an iterative approach with only a single code node.
  • When experimenting with recursion, make sure to define a termination condition first. Also, be aware of the "Restart workspace" link in the n8n Dashboard.
  • Learn more about Recursion on Wikipedia.

Set up steps

  • Optional: Set "numberOfDiscs" in node "Set number of discs"
  • Execute workflow

Recursive Algorithms with Sub-workflows: Towers of Hanoi Demo

This n8n workflow demonstrates how to implement recursive algorithms using sub-workflows, specifically showcasing the classic Towers of Hanoi puzzle. It utilizes the "Execute Sub-workflow" node to simulate recursive calls, making complex problems manageable and modular.

What it does

This workflow acts as a foundational example for recursive logic in n8n. While the provided JSON is a skeleton, its structure indicates the following intended steps for a Towers of Hanoi implementation:

  1. Trigger: The workflow can be initiated either manually or by another workflow (acting as a sub-workflow call).
  2. Input Processing: An "Edit Fields (Set)" node would typically prepare the necessary parameters for the recursive function (e.g., number of disks, source peg, destination peg, auxiliary peg).
  3. Base Case Check: An "If" node is crucial for any recursive algorithm. It checks for the base case (e.g., if there's only one disk to move).
  4. Recursive Calls (Sub-workflows): If the base case is not met, the "Execute Sub-workflow" node would be called multiple times, simulating the recursive steps of moving n-1 disks, then moving the largest disk, and finally moving the remaining n-1 disks. Each call would pass updated parameters.
  5. Code Execution (Optional): A "Code" node could be used for more complex logic, state management, or output formatting within the recursive steps.
  6. Output: The final result or a specific action would be performed once the recursion unwinds.

Prerequisites/Requirements

  • n8n Instance: A running n8n instance (self-hosted or cloud).
  • Understanding of Recursion: Familiarity with recursive algorithms is beneficial to fully grasp the workflow's purpose.
  • Sub-workflow Setup: To fully implement the Towers of Hanoi, you would need to create a separate sub-workflow that this main workflow calls recursively. The JSON provided is for the calling workflow, not the sub-workflow itself.

Setup/Usage

  1. Import the workflow: Import the provided JSON into your n8n instance.
  2. Create a Sub-workflow: Design a separate n8n workflow that represents the "recursive function" for the Towers of Hanoi. This sub-workflow should:
    • Start with an "Execute Workflow Trigger" node to receive input from the main workflow.
    • Contain an "If" node to check for the base case (e.g., numDisks === 1).
    • If not the base case, it should call itself (or rather, the main workflow which then calls it again) via an "Execute Sub-workflow" node with modified parameters, simulating the recursive steps.
    • Perform the "move" action (e.g., log a message like "Move disk from A to B") for the base case or the largest disk.
  3. Configure "Execute Sub-workflow" nodes: In the main workflow, configure the "Execute Sub-workflow" node(s) to point to the ID of your newly created sub-workflow.
  4. Define Inputs: Use the "Edit Fields (Set)" node to define the initial parameters for the Towers of Hanoi puzzle (e.g., numDisks, sourcePeg, destinationPeg, auxiliaryPeg).
  5. Activate and Execute: Activate the workflow and execute it manually to see the recursive calls in action in the execution logs.

Related Templates

AI multi-agent executive team for entrepreneurs with Gemini, Perplexity and WhatsApp

This workflow is an AI-powered multi-agent system built for startup founders and small business owners who want to automate decision-making, accountability, research, and communication, all through WhatsApp. The โ€œvirtual executive team,โ€ is designed to help small teams to work smarter. This workflow sends you market analysis, market and sales tips, It can also monitor what your competitors are doing using perplexity (Research agent) and help you stay a head, or make better decisions. And when you feeling stuck with your start-up accountability director is creative enough to break the barrier ๐ŸŽฏ Core Features ๐Ÿง‘โ€๐Ÿ’ผ 1. President (Super Agent) Acts as the main controller that coordinates all sub-agents. Routes messages, assigns tasks, and ensures workflow synchronization between the AI Directors. ๐Ÿ“Š 2. Sales & Marketing Director Uses SerpAPI to search for market opportunities, leads, and trends. Suggests marketing campaigns, keywords, or outreach ideas. Can analyze current engagement metrics to adjust content strategy. ๐Ÿ•ต๏ธโ€โ™€๏ธ 3. Business Research Director Powered by Perplexity AI for competitive and market analysis. Monitors competitor moves, social media engagement, and product changes. Provides concise insights to help the founder adapt and stay ahead. โฐ 4. Accountability Director Keeps the founder and executive team on track. Sends motivational nudges, task reminders, and progress reports. Promotes consistency and discipline โ€” key traits for early-stage success. ๐Ÿ—“๏ธ 5. Executive Secretary Handles scheduling, email drafting, and reminders. Connects with Google Calendar, Gmail, and Sheets through OAuth. Automates follow-ups, meeting summaries, and notifications directly via WhatsApp. ๐Ÿ’ฌ WhatsApp as the Main Interface Interact naturally with your AI team through WhatsApp Business API. All responses, updates, and summaries are delivered to your chat. Ideal for founders who want to manage operations on the go. โš™๏ธ How It Works Trigger: The workflow starts from a WhatsApp Trigger node (via Meta Developer Account). Routing: The President agent analyzes the incoming message and determines which Director should handle it. Processing: Marketing or sales queries go to the Sales & Marketing Director. Research questions are handled by the Business Research Director. Accountability tasks are assigned to the Accountability Director. Scheduling or communication requests are managed by the Secretary. Collaboration: Each sub-agent returns results to the President, who summarizes and sends the reply back via WhatsApp. Memory: Context is maintained between sessions, ensuring personalized and coherent communication. ๐Ÿงฉ Integrations Required Gemini API โ€“ for general intelligence and task reasoning Supabase- for RAG and postgres persistent memory Perplexity API โ€“ for business and competitor analysis SerpAPI โ€“ for market research and opportunity scouting Google OAuth โ€“ to connect Sheets, Calendar, and Gmail WhatsApp Business API โ€“ for message triggers and responses ๐Ÿš€ Benefits Acts like a team of tireless employees available 24/7. Saves time by automating research, reminders, and communication. Enhances accountability and strategy consistency for founders. Keeps operations centralized in a simple WhatsApp interface. ๐Ÿงฐ Setup Steps Create API credentials for: WhatsApp (via Meta Developer Account) Gemini, Perplexity, and SerpAPI Google OAuth (Sheets, Calendar, Gmail) Create a supabase account at supabase Add the credentials in the corresponding n8n nodes. Customize the system prompts for each Director based on your startupโ€™s needs. Activate and start interacting with your virtual executive team on WhatsApp. Use Case You are a small organisation or start-up that can not afford hiring; marketing department, research department and secretar office, then this workflow is for you ๐Ÿ’ก Need Customization? Want to tailor it for your startup or integrate with CRM tools like Notion or HubSpot? You can easily extend the workflow or contact the creator for personalized support. Consider adjusting the system prompt to suite your business

ShadrackBy Shadrack
331

๐ŸŽ“ How to transform unstructured email data into structured format with AI agent

This workflow automates the process of extracting structured, usable information from unstructured email messages across multiple platforms. It connects directly to Gmail, Outlook, and IMAP accounts, retrieves incoming emails, and sends their content to an AI-powered parsing agent built on OpenAI GPT models. The AI agent analyzes each email, identifies relevant details, and returns a clean JSON structure containing key fields: From โ€“ senderโ€™s email address To โ€“ recipientโ€™s email address Subject โ€“ email subject line Summary โ€“ short AI-generated summary of the email body The extracted information is then automatically inserted into an n8n Data Table, creating a structured database of email metadata and summaries ready for indexing, reporting, or integration with other tools. --- Key Benefits โœ… Full Automation: Eliminates manual reading and data entry from incoming emails. โœ… Multi-Source Integration: Handles data from different email providers seamlessly. โœ… AI-Driven Accuracy: Uses advanced language models to interpret complex or unformatted content. โœ… Structured Storage: Creates a standardized, query-ready dataset from previously unstructured text. โœ… Time Efficiency: Processes emails in real time, improving productivity and response speed. *โœ… Scalability: Easily extendable to handle additional sources or extract more data fields. --- How it works This workflow automates the transformation of unstructured email data into a structured, queryable format. It operates through a series of connected steps: Email Triggering: The workflow is initiated by one of three different email triggers (Gmail, Microsoft Outlook, or a generic IMAP account), which constantly monitor for new incoming emails. AI-Powered Parsing & Structuring: When a new email is detected, its raw, unstructured content is passed to a central "Parsing Agent." This agent uses a specified OpenAI language model to intelligently analyze the email text. Data Extraction & Standardization: Following a predefined system prompt, the AI agent extracts key information from the email, such as the sender, recipient, subject, and a generated summary. It then forces the output into a strict JSON structure using a "Structured Output Parser" node, ensuring data consistency. Data Storage: Finally, the clean, structured data (the from, to, subject, and summarize fields) is inserted as a new row into a specified n8n Data Table, creating a searchable and reportable database of email information. --- Set up steps To implement this workflow, follow these configuration steps: Prepare the Data Table: Create a new Data Table within n8n. Define the columns with the following names and string type: From, To, Subject, and Summary. Configure Email Credentials: Set up the credential connections for the email services you wish to use (Gmail OAuth2, Microsoft Outlook OAuth2, and/or IMAP). Ensure the accounts have the necessary permissions to read emails. Configure AI Model Credentials: Set up the OpenAI API credential with a valid API key. The workflow is configured to use the model, but this can be changed in the respective nodes if needed. Connect the Nodes: The workflow canvas is already correctly wired. Visually confirm that the email triggers are connected to the "Parsing Agent," which is connected to the "Insert row" (Data Table) node. Also, ensure the "OpenAI Chat Model" and "Structured Output Parser" are connected to the "Parsing Agent" as its AI model and output parser, respectively. Activate the Workflow: Save the workflow and toggle the "Active" switch to ON. The triggers will begin polling for new emails according to their schedule (e.g., every minute), and the automation will start processing incoming messages. --- Need help customizing? Contact me for consulting and support or add me on Linkedin.

DavideBy Davide
1616

Automate Reddit brand monitoring & responses with GPT-4o-mini, Sheets & Slack

How it Works This workflow automates intelligent Reddit marketing by monitoring brand mentions, analyzing sentiment with AI, and engaging authentically with communities. Every 24 hours, the system searches Reddit for posts containing your configured brand keywords across all subreddits, finding up to 50 of the newest mentions to analyze. Each discovered post is sent to OpenAI's GPT-4o-mini model for comprehensive analysis. The AI evaluates sentiment (positive/neutral/negative), assigns an engagement score (0-100), determines relevance to your brand, and generates contextual, helpful responses that add genuine value to the conversation. It also classifies the response type (educational/supportive/promotional) and provides reasoning for whether engagement is appropriate. The workflow intelligently filters posts using a multi-criteria system: only posts that are relevant to your brand, score above 60 in engagement quality, and warrant a response type other than "pass" proceed to engagement. This prevents spam and ensures every interaction is meaningful. Selected posts are processed one at a time through a loop to respect Reddit's rate limits. For each worthy post, the AI-generated comment is posted, and complete interaction data is logged to Google Sheets including timestamp, post details, sentiment, engagement scores, and success status. This creates a permanent audit trail and analytics database. At the end of each run, the workflow aggregates all data into a comprehensive daily summary report with total posts analyzed, comments posted, engagement rate, sentiment breakdown, and the top 5 engagement opportunities ranked by score. This report is automatically sent to Slack with formatted metrics, giving your team instant visibility into your Reddit marketing performance. --- Who is this for? Brand managers and marketing teams needing automated social listening and engagement on Reddit Community managers responsible for authentic brand presence across multiple subreddits Startup founders and growth marketers who want to scale Reddit marketing without hiring a team PR and reputation teams monitoring brand sentiment and responding to discussions in real-time Product marketers seeking organic engagement opportunities in product-related communities Any business that wants to build authentic Reddit presence while avoiding spammy marketing tactics --- Setup Steps Setup time: Approx. 30-40 minutes (credential configuration, keyword setup, Google Sheets creation, Slack integration) Requirements: Reddit account with OAuth2 application credentials (create at reddit.com/prefs/apps) OpenAI API key with GPT-4o-mini access Google account with a new Google Sheet for tracking interactions Slack workspace with posting permissions to a marketing/monitoring channel Brand keywords and subreddit strategy prepared Create Reddit OAuth Application: Visit reddit.com/prefs/apps, create a "script" type app, and obtain your client ID and secret Configure Reddit Credentials in n8n: Add Reddit OAuth2 credentials with your app credentials and authorize access Set up OpenAI API: Obtain API key from platform.openai.com and configure in n8n OpenAI credentials Create Google Sheet: Set up a new sheet with columns: timestamp, postId, postTitle, subreddit, postUrl, sentiment, engagementScore, responseType, commentPosted, reasoning Configure these nodes: Brand Keywords Config: Edit the JavaScript code to include your brand name, product names, and relevant industry keywords Search Brand Mentions: Adjust the limit (default 50) and sort preference based on your needs AI Post Analysis: Customize the prompt to match your brand voice and engagement guidelines Filter Engagement-Worthy: Adjust the engagementScore threshold (default 60) based on your quality standards Loop Through Posts: Configure max iterations and batch size for rate limit compliance Log to Google Sheets: Replace YOURSHEETID with your actual Google Sheets document ID Send Slack Report: Replace YOURCHANNELID with your Slack channel ID Test the workflow: Run manually first to verify all connections work and adjust AI prompts Activate for daily runs: Once tested, activate the Schedule Trigger to run automatically every 24 hours --- Node Descriptions (10 words each) Daily Marketing Check - Schedule trigger runs workflow every 24 hours automatically daily Brand Keywords Config - JavaScript code node defining brand keywords to monitor Reddit Search Brand Mentions - Reddit node searches all subreddits for brand keyword mentions AI Post Analysis - OpenAI analyzes sentiment, relevance, generates contextual helpful comment responses Filter Engagement-Worthy - Conditional node filters only high-quality relevant posts worth engaging Loop Through Posts - Split in batches processes each post individually respecting limits Post Helpful Comment - Reddit node posts AI-generated comment to worthy Reddit discussions Log to Google Sheets - Appends all interaction data to spreadsheet for permanent tracking Generate Daily Summary - JavaScript aggregates metrics, sentiment breakdown, generates comprehensive daily report Send Slack Report - Posts formatted daily summary with metrics to team Slack channel

Daniel ShashkoBy Daniel Shashko
679