Recursion Tree Visualizer
Visualize recursive call trees step by step
Updated
What is the Recursion Tree Visualizer?
The Recursion Tree Visualizer lets you write any recursive JavaScript function, execute it with your own arguments, and watch the entire call tree animate step by step. Every function call appears as a node, every return is highlighted, and the live call-stack panel shows exactly which frame is active at each moment.
Recursion is one of the hardest concepts for new programmers to internalize. Textbooks draw static tree diagrams, but they cannot show the order in which nodes are created or how the call stack grows and shrinks. This tool fills that gap by turning your code into an interactive, playable animation you can scrub forward and backward at any speed.
Six built-in presets cover the most commonly studied recursive algorithms: Fibonacci, Factorial, GCD (Euclidean), Pascal's Triangle binomial coefficient, Tower of Hanoi, and Power of Two. Pick one to start instantly, then edit the code or swap in your own function to explore anything else.
Each node is color-coded by recursion depth so you can immediately see how deep the call chain goes. Return values appear beneath their nodes once a call completes. The step slider and keyboard shortcuts (arrow keys for single steps, spacebar to play/pause, Home/End to jump) give you full control over the pace.
The visualization supports pan and zoom so large trees remain navigable. Drag to pan the canvas, scroll to zoom in or out, and use the Fit View button to auto-frame the entire tree in the viewport.
When you have finished exploring, export the complete call data as a JSON file. The export includes every call record with arguments, depth, return value, and parent-child relationships, making it useful for assignments, presentations, or further analysis.
Everything runs entirely in your browser. Your code is never sent to a server.
How it works
1. Code instrumentation
When you click Execute & Visualize, the tool parses your function declaration to extract its name. It then performs two source-level transformations: the original declaration is renamed to a private alias (e.g., fib becomes __orig_fib), and every recursive call to the original name is replaced with a call to a tracking wrapper named __tracked.
2. Safe execution
The rewritten source is compiled into a sandboxed function via new Function. Before running, the tool injects guard logic that enforces two configurable limits:
- Max Depth -- if the call stack exceeds this depth, execution stops with a clear error message suggesting you check your base case.
- Max Calls -- if the total number of recorded calls exceeds this limit, execution halts to prevent the browser from freezing.
These guards protect against accidental infinite recursion or excessively large inputs.
3. Call recording
Every time __tracked is invoked, it records an entry containing a unique ID, the parent call's ID, the arguments, and the current stack depth. When the call returns, the recorded entry is updated with the return value. The result is a flat array of CallRecord objects that captures the full execution trace.
4. Tree construction
The flat call records are assembled into a hierarchical tree. Each record's parentId links it to its caller. The root node has no parent. Children are attached in the order they were called, preserving the left-to-right structure that matches how the recursion unfolds.
5. Layout algorithm
A bottom-up, width-packing algorithm assigns horizontal positions:
- Leaf nodes are sized to their content width.
- Each parent's subtree width is the sum of its children's widths plus the horizontal gap between siblings, or the parent's own content width -- whichever is larger.
- Starting from the root, children are centered under their parent within the allocated subtree width.
This produces a compact, non-overlapping layout for trees of any shape.
6. Step generation
The tool replays the execution trace to generate an interleaved list of call and return steps. A call step appears when a node first enters the tree; a return step appears when that node's value is computed. The order matches the actual program execution, including depth-first traversal and backtracking.
7. Animated playback
At any step index, the tool computes which nodes are visible, which have returned, and which is currently active. The SVG tree renders only the nodes present at that step, with visual cues:
- Active node has an amber glow and highlighted edge.
- Returned nodes become muted with dashed edges.
- Depth coloring distinguishes levels across the full palette.
- Return values appear beneath nodes once they complete.
The step slider, playback controls, and keyboard shortcuts all operate on this step-index model, making the animation fully reversible and seekable.
Examples
Visualize Fibonacci recursion tree
See every branch of fib(7) unfold step by step, from the initial call down to each base case return.
Trace the Euclidean GCD algorithm
Watch gcd(48, 18) recurse through modulo reductions in a linear chain until it reaches the base case.
Explore Pascal's Triangle binomial coefficient
Compute C(5,3) recursively and observe the branching pattern that mirrors the combinatorial identity.
Frequently asked questions
What JavaScript features does the Recursion Tree Visualizer support?
What JavaScript features does the Recursion Tree Visualizer support?
The tool supports standard JavaScript function declarations with named recursion. You can use numbers, strings, booleans, and arrays as arguments. Control flow constructs like if/else, ternary operators, and arithmetic all work normally. The tool does not support arrow functions, async/await, or module imports -- the function must be a self-contained function name(params) { ... } declaration.
Why does my function throw a "Maximum recursion depth exceeded" error?
Why does my function throw a "Maximum recursion depth exceeded" error?
This means the call stack reached the Max Depth limit you set (default 20). It usually indicates either the base case is missing or the input is too large for the configured limit. Double-check that your function has a reachable termination condition, then try increasing the Max Depth slider or reducing the input size.
Can I visualize mutual recursion (two functions calling each other)?
Can I visualize mutual recursion (two functions calling each other)?
Not currently. The tool instruments a single named function and replaces self-recursive calls. Mutual recursion between two or more functions requires a different instrumentation strategy. For now, rewrite the logic as a single function with an extra parameter to distinguish the roles, or visualize each function separately.
Is my code sent to a server?
Is my code sent to a server?
No. All instrumentation, execution, tree layout, and rendering happen entirely in your browser. The new Function call is sandboxed client-side. Your code never leaves your device.
How large a recursion tree can the tool handle?
How large a recursion tree can the tool handle?
The practical limit depends on your browser's performance. The tool enforces a hard cap of 50 for Max Depth and 5000 for Max Calls to prevent freezing. Most common examples (Fibonacci up to n=10, Factorial up to n=20, GCD with moderately large inputs) render smoothly. Very large trees may become slow to render in SVG -- in that case, reduce the input or increase only the depth limit.
What do the colors in the tree represent?
What do the colors in the tree represent?
Each recursion depth level gets a distinct color from a rotating ten-color palette. Depth 0 is blue, depth 1 is purple, depth 2 is pink, and so on. The small numeric badge on each node's corner also shows the exact depth. This makes it easy to spot deep recursion chains and compare branching patterns across algorithms.
Can I export or save the visualization?
Can I export or save the visualization?
Yes. After executing a function, an Export JSON button appears below the tree. It downloads a JSON file containing every call record with its ID, parent ID, arguments, depth, and return value, along with summary statistics like total calls, max depth, and final result. The tree SVG itself can be captured via your browser's screenshot or developer tools.
How do I control the playback speed?
How do I control the playback speed?
Use the Speed slider below the playback controls. Dragging it right increases the frame rate. You can also step through manually with the left/right arrow keys on your keyboard, press spacebar to toggle play/pause, or use Home and End to jump to the first or last step. The step slider lets you drag to any point in the animation instantly.
Why are some nodes shown with dashed edges and muted colors?
Why are some nodes shown with dashed edges and muted colors?
Dashed, muted nodes have already returned -- their computation is complete and their return value is known. This visual distinction helps you focus on the currently active branch of the recursion. You can toggle the display of return values using the Return values switch.
What does the call stack panel show?
What does the call stack panel show?
The call stack panel on the right side of the tree displays the current execution stack at any animation step. The topmost entry is the active function call, and entries below it are the callers waiting for results. Each entry shows the depth number, its arguments, and a colored bar matching the depth palette. This mirrors what you would see in a debugger's call stack window.
Related tools
More utilities you might find handy.
Binary Search Visualizer
Visualize binary search algorithm step by step
Regex Visualizer — Railroad Diagram Generator for Regular Expressions
Free online regex visualizer that renders any JavaScript regular expression as an interactive railroad diagram, with a plain-English breakdown, live match tester, and ReDoS warnings — all in your browser.
Shape Drawer
Create and edit geometric shapes with precise measurements, live calculations, and export to SVG, CSS, or HTML