What you implemented is this (in pseudo code):

display(line) {
  if no_x_in(line) {
     print(line)  // instance output and recursion stop 
  } 
  display(replace_first_x_with_0(line))  // recursive call
  display(replace_first_x_with_1(line))  // recursive call
}
  • If the string in line contains no x symbols anymore you can output the string and your recursive descent can stop.

  • If not, the problem instance is reduced from a line with n times many x symbols into two smaller instances, each with n - 1 many x symbols,

    • one with the x replaced by a 0 symbol and
    • one with the x replaced by a 1 symbol.

which result into a recursive call each. As there are only finite many x symbols in the finite input string, the recursive calls will stop at some point, and the resulting call tree is finite as well.

For your example the call tree is like this:

display('xx') -> issues calls to display('0x') and display('1x')
|
+-> display('0x') -> issues calls to display('00') and display('01')
|   |
|   +-> display('00') -> output, stop
|   +-> display('01') -> output, stop
|
+-> display('1x') -> issues calls to display('10') and display('11')
    |
    +-> display('10') -> output, stop
    +-> display('11') -> output, stop
Answer from mvw on Stack Overflow
🌐
VisuAlgo
visualgo.net › en › bst
Binary Search Tree, AVL Tree - VisuAlgo
Example: In the background, we have N5 = 20 vertices but we know that we can squeeze 43 more vertices (up to N = 63) before we have a perfect binary tree of height h = 5. ... Nh = 1 + Nh-1 + Nh-2 (formula for minimum-size AVL tree of height h) Nh > 1 + 2*Nh-2 (as Nh-1 > Nh-2) Nh > 2*Nh-2 (obviously) Nh > 4*Nh-4 (recursive) Nh > 8*Nh-6 (another recursive step) ...
🌐
Tree Converter
treeconverter.com
Binary Tree and Graph Visualizer | Tree Converter
Pick the middle element as root, recurse on halves. Visualizing the tree you built checks that heights stay balanced as expected.
Discussions

c - Visualizing recursion for binary tree - Stack Overflow
Write a recursive function that displays all the binary (base 2) numbers represented by a string of xs, 0s, and 1s. The xs represent digits that can be either 0 or 1. For example, the string xx More on stackoverflow.com
🌐 stackoverflow.com
Advice on visualizing recursion
Imagine each call is being placed into a stack (the processor stack) More on reddit.com
🌐 r/leetcode
37
57
August 21, 2022
Depth First Search from the Ground Up: How to Visualize Recursion and Solve Problems with Depth-First Search
Sup everyone! TLDR: click here to learn how to visualize recursion, and follow a structured approach to solving binary tree problems using… More on reddit.com
🌐 r/leetcode
6
48
May 14, 2024
algorithm - Is there any way to have simple ascii visualization of binary search tree? - Stack Overflow
I have developed a binary search tree structure and I want to add some function which can visualize the tree. The code below belongs to Binary Search Tree: class Node(object): def __init__(self, More on stackoverflow.com
🌐 stackoverflow.com
People also ask

What is the difference between a binary tree and a binary search tree?
A binary tree simply restricts each node to at most two children, with no ordering. A binary search tree adds the rule that everything in the left subtree is smaller and everything in the right subtree is larger, which is what makes searching fast.
🌐
coddy.tech
coddy.tech › visualizations › data structures › binary tree
Binary Tree Visualization | Coddy
What is a complete binary tree?
A complete binary tree has every level fully filled except possibly the last, which is filled from left to right. This shape lets the tree be stored compactly in an array (no child pointers needed), which is how binary heaps are implemented.
🌐
coddy.tech
coddy.tech › visualizations › data structures › binary tree
Binary Tree Visualization | Coddy
When should I use a binary tree instead of an array or hash table?
Reach for a tree when your data is naturally hierarchical or when you need ordered operations like range queries and sorted iteration, which hash tables cannot give you. If you only need fast key lookup with no ordering, a hash table's O(1) average access beats a tree, and for flat data an array is simpler and more cache-friendly.
🌐
coddy.tech
coddy.tech › visualizations › data structures › binary tree
Binary Tree Visualization | Coddy
🌐
AlgoCademy
algocademy.com › blog › introduction-to-recursion-trees-and-visualization
Introduction to Recursion Trees and Visualization – AlgoCademy Blog
Python libraries like graphviz or networkx can be used to generate recursion trees programmatically. Online visualization tools like Recursion Visualizer allow you to input your code and see the recursion tree generated in real-time.
🌐
Medium
medium.com › @yasamin_18817 › visualizing-recursive-binary-tree-traversal-b199fbab0256
Visualizing Recursive Binary Tree Traversal | by Yasamin Nouri Jelyani | Medium
February 24, 2025 - The empty list is set to the right subtree. Then, the stack returns the value of the pre-order traversal for this left sub-tree to the next item in the stack.
🌐
VisuAlgo
visualgo.net › en › recursion
Recursion Tree and DAG (Dynamic Programming/DP) - VisuAlgo
Only one of the two possible branches ... tree = recursion DAG situation. The time complexity if Θ(log n) as we keep halving the search space each time. The worst-case happens when a2 is not found in sorted array a1. In this visualization, we randomize the content of sorted array a1 and the value to be searched a2. TBC: In the near future, we will draw the entire Θ(n) search space (both left and right branches at each vertex) and highlight the efficient Θ(log n) path taken by Binary Search on ...
Find elsewhere
🌐
Towards AI
pub.towardsai.net › visualizing-recursion-trees-cb08103b54fe
Visualizing Recursion Trees. Reflections on Vibe Coding | by Han Qi | Towards AI
March 25, 2025 - https://visualgo.net/en/recursion | Can’t figure out how to setup global variables properly · https://github.com/brpapa/recursion-tree-visualizer | Forces pasted functions to be nameddef fn , thus requiring function names in recursive body to be edited too.
🌐
Reddit
reddit.com › r/leetcode › advice on visualizing recursion
r/leetcode on Reddit: Advice on visualizing recursion
August 21, 2022 -

Hey Guys,
I have been solving a lot of Tree related problems lately. Of course Recursion is a technique which will make it easy , right? The problem I am facing is that i just cannot visualize recursion through the tree. I mean everyone knows what is recursion but its not just "clicking". I have gone through a lot of YT videos and of course discussion section but all i can do is admire how amazingly brilliant folks are and how dumb i am. Idk if any of this makes sense, would appreciate some advice!

🌐
GitHub
github.com › EliahKagan › TreeTraversalAnimations
GitHub - EliahKagan/TreeTraversalAnimations: Simple binary-tree traversal visualizer · GitHub
This program demonstrates most ... binary tree without parent pointers: straightforward recursion; two kinds of iterative techniques; and iterative implementations of recursive techniques, using a state machine. It does not cover mutating techniques such as Morris traversal, even though such approaches are sometimes useful and would be quite interesting to visualize, since they ...
Author: EliahKagan
🌐
Coddy.Tech
coddy.tech › visualizations › data structures › binary tree
Binary Tree Visualization | Coddy
July 1, 2026 - Interactive binary tree visualization: watch nodes fill level by level and step through an in-order traversal, with structure, terminology, and code.
🌐
Labuladong
labuladong.online › en › algo › data-structure-basic › binary-tree-traverse-basic
Binary Tree Recursive/Level Traversal
July 14, 2026 - You can think of the traverse recursive function as a pointer moving around the binary tree. The visualization panel below shows how this algorithm works step by step.
🌐
GeeksforGeeks
geeksforgeeks.org › dsa › bottom-view-of-a-binary-tree-using-recursion
Bottom View of a Binary Tree using Recursion - GeeksforGeeks
July 12, 2025 - ... We can do so by using recursion and 2 arrays each with size 2n+1(for worst case), where n = number of elements in the given tree. Here, we take a variable x which determines its Horizontal Distance.
🌐
Eva Maria Kiss
evamariakiss.de › apps › bstlearner_v1.php
BSTLearner - Interactive Binary Search Tree Visualization | Prof. E. Kiss, HS KL
class BST(): def __init__(self): self.root = None # Root of the tree self.list = [] # Elements of the tree as list def insert(self, k): ''' Insert a key ''' def search(self, x, k): ''' Search for a key k starting at node x ''' def find(self, k): return self.search(self.root, k) def transplant(self, u, v): ''' Replace subtree u with subtree v ''' def delete(self, k): '''Delete node with key k from tree ''' def visualize(self, node = None): ''' Visualize the tree using graphviz ''' As illustration, we show the implementation of the TREE-SEARCH pseudocode given in Cormen [1] in Python. A recursive search for key k starting at a node x can be implemented using the following pseudocode: If the starting node x is null, we have reached a leaf and are done.
🌐
Medium
medium.com › @siddharthgupta555t › finally-understanding-recursion-and-binary-search-trees-857c85e72978
Finally Understanding: Recursion and Binary Search Trees | by Siddharth G | Medium
November 13, 2020 - Eventually, recursively, we get to a point where the ‘sub trees’ are just nodes. which is why the node is so important in the tree as well. ... Now lets look at one of the methods used in BST’s, called insertion. ... The first method of the Binary Search Tree that we will be discussing about is how to insert nodes.
🌐
Csanim
csanim.com › tutorials › inorder-preorder-and-postorder-tree-traversals-animated-guide
Depth First Traversal: Inorder, Preorder and Postorder tree traversals - Animated guide
For explanation purposes we are going to assume we have a tree with a single root node with no leaves since the same functionality is repeated across every recursion. ... def in_order(root): if root: in_order(root.left) print(root.val) in_order(root.right) # end # Initialize the tree root = Node(1) in_order(root) We first initialize our Binary Search Tree with a single node at line 9:
🌐
Reddit
reddit.com › r/leetcode › depth first search from the ground up: how to visualize recursion and solve problems with depth-first search
r/leetcode on Reddit: Depth First Search from the Ground Up: How to Visualize Recursion and Solve Problems with Depth-First Search
May 14, 2024 - I wrote an in-depth guide on how ... trees). It starts with an animation that shows you how to visualize how a recursive depth-first search algorithm finds the sum of all nodes in a binary tree....
🌐
Crackr
crackr.dev › visualize › recursion-tree
Recursion Tree Visualizer | Free Recursion Tree Generator
Free recursion tree visualizer and generator. Visualize Fibonacci, merge sort, and binary search recursion trees step by step. See memoization collapse trees into DAGs.
🌐
See Algorithms
see-algorithms.com › data-structures › BST
Binary Search Tree Visualizer | Interactive BST Operations
Interactive BST tool. Insert, search, and delete nodes and visualize how the tree structure changes. Understand O(log n) vs O(n) search.
Top answer
1 of 3
2

I think a recursive traversal will be easiest. With a non-recursive solution you end up having to manage the stack yourself.

Here's some code in C#, which you should be able to port to Python easily enough:

string Traverse(Node node)
{
    string rslt = "";
    bool hasRightNode = false;
    bool hasLeftNode = false;
    if (node.Right != null)
    {
        hasRightNode = true;
        rslt = rslt + "(";
        rslt = rslt + Traverse(node.Right);
    }
    if (node.Left != null)
    {
        hasLeftNode = true;
        if (hasRightNode)
        {
            rslt = rslt + ",";
        }
        else
        {
            rslt = rslt + "(";
        }
        rslt = rslt + Traverse(node.Left);
    }
    if (hasLeftNode || hasRightNode)
    {
        rslt = rslt + ")";
    }
    rslt = rslt + node.Value;
    return rslt;
}

The only thing missing is the final semicolon. You can call it with:

string format = Traverse(root) + ";";

Given the tree that you posted, that outputs the expected format string.

Note that I use string concatenation here, which is sub-optimal in C#. If this were a production program, I'd probably use a StringBuilder object to avoid concatenation. I'm not familiar enough with Python to say how best to compose strings in that language.

2 of 3
0

According to Mr.Jim Mischel sample code in C#, I added the following function in the Node class:

def R_postorder(self):
    ret = ''
    if self:
        hasRightChild = False
        hasLeftChild = False
        if self.rightChild:
            hasRightChild = True
            ret += '('
            ret += self.rightChild.RLV()

        if self.leftChild:
            hasLeftChild = True
            if hasRightChild:
                ret += ','
            else:
                ret += '('
            ret += self.leftChild.RLV()
        if hasRightChild or hasLeftChild:
            ret += ')'
        ret += str(self.data)
    return ret

and I also added the R_postorder to the BST class:

def R_postorder(self):
    ret = self.rootNode.RLV()
    ret += ';'
    return ret

By using the returned value of bst.R_postorder() as an input to create the tree_format variable, the right outcome would be achieved.

🌐
DEV Community
dev.to › bishalsarang › visualize-recursion-tree-with-animation-in-python-5357
Visualize Recursion Tree with Animation in Python - DEV Community
April 2, 2020 - Here is the github link to the package: https://github.com/Bishalsarang/Recursion-Tree-Visualizer · Here are some more examples on coin change problem, fibonacci, constructing binary string, subset sum and combinations problems: https://github.com/Bishalsarang/Recursion-Tree-Visualizer/tree/master/examples Hope you will enjoy the package.