Instead of externally keeping a list you can build it as you go.

def list_parentals(tree, element, parents):
    this, children = tree
    new_parents = [this] + parents
    if this == element:
        return new_parents
    else:
        for child in children:
            x = list_parentals(child, element, new_parents)
            # If x is not None, return it
            if x:
                return x

list_parentals(t, 'George', [])
# ['George', 'Fanny', 'Eric', 'Alan']
Answer from Henry on Stack Overflow
🌐
GeeksforGeeks
geeksforgeeks.org › dsa › recursion-on-trees-in-python
Recursion on Trees in Python - GeeksforGeeks
July 23, 2025 - The size of a tree is the total number of nodes in the tree, including the root node and all its descendants. This can be calculated recursively by summing up the sizes of the left and right subtrees and adding 1 for the root node.
🌐
Reddit
reddit.com › r/learnprogramming › tree recursion in python
r/learnprogramming on Reddit: tree recursion in python
December 11, 2022 -

Hello, an independent learner here. After struggling with some Leetcode problems on tree recursion in python, I'm wondering about resources for getting better at it. Any book or website recommendations? For example, I plugged a few users' solutions into the 'visualize python' website to try to understand the process better, but I'm still not getting it. In the recursion stack, values can be passed around ('up' and 'down' the tree?) . Just want to understand this better. I did the first couple chapters of SICP a while back--maybe I should go back to that unless someone knows of other good material as well. Thanks.

Top answer
1 of 2
1

Instead of externally keeping a list you can build it as you go.

def list_parentals(tree, element, parents):
    this, children = tree
    new_parents = [this] + parents
    if this == element:
        return new_parents
    else:
        for child in children:
            x = list_parentals(child, element, new_parents)
            # If x is not None, return it
            if x:
                return x

list_parentals(t, 'George', [])
# ['George', 'Fanny', 'Eric', 'Alan']
2 of 2
0

For "my recursive function returns None", that is a very, very classical problem. You'll find hundred of detailed answers about that on SO searching these words.

But in short, a recursive function must return something always, not just when it found something. Typically, on such an example, you must return a result when you found the correct leaf. But if you don't want that result to be lost, then, you must also return something when you call that recursion that found the leaf. And when you call that recursion that called that recursion that found the leaf.

Keep in mind that what you get as a final result is the return value of the first call to list_parentals. If that first call doesn't return anything, then, it doesn't matter that some recursive subcalls did.

Secondly, the way to build such a path is precisely to take advantage of the recursion. Trying to create a list in a global variable when you find a matching leaf is not easy. And you may end up trying to compute that with a iterative algorithm, when the whole point of recursion is to do that for you.

Here is a working recursive method (I tried to keep it as close are your own code as possible)

tree=('Alan', [('Bob', [('Chris', []), ('Debbie', [('Cindy', [])])]), ('Eric', [('Dan', []), ('Fanny', [('George', [])])]), ('Hannah', [])])

def list_parentals(tree, element):
    if tree[0] == element:
        return [element]
    else:
        for child in tree[1]:
            sub=list_parentals(child, element)
            if sub:
                return [tree[0]] + sub
        return []

r=list_parentals(tree, 'George')
print(f"{r=}")

The logic of that is that list_parental(tree, 'George') returns the path in tree to leaf 'George', or [] (or None, or False, doesn't matter) if no such leaf is found. So (just think of it as a mathematical expression, not as code, for now), list_parental(('Alan', [('Bob', [('Chris', []), ('Debbie', [('Cindy', [])])]), ('Eric', [('Dan', []), ('Fanny', [('George', [])])]), ('Hannah', [])]), 'George') is just Alan plus `list_parental(('Eric', [('Dan', []), ('Fanny', [('George', [])])]), 'George').

``list_parental(('Eric', [('Dan', []), ('Fanny', [('George', [])])]), 'George')is justEricpluslist_parental(('Fanny', [('George', [])]), 'George')`.

list_parental(('Fanny', [('George', [])]), 'George') is just Fanny plus list_parental(('George', []), 'George').

list_parental(('George', []), 'George') is just George.

To keep this consistent, all returns must be lists.

Hence my code.

list_parental(tree, leafName) is [leafName] is the root of the tree match leafName.

Else list_parental(tree, leafName) is [tree[0]] + list_parental(child, leafName) if one of the child contains leafName, that is if list_parental(child, leafName) is not empty.

🌐
Vercel
recursion.vercel.app
Recursion Tree Visualizer
Input the source code of any recursive function in javascript, python or golang and visualize its recursion tree
🌐
University of Toronto
cs.toronto.edu › ~david › course-notes › csc110-111 › 15-trees › 02-tree-recursion.html
15.2 Recursion on Trees
This is quite similar to how we defined the size function for nested lists, and translates naturally into a recursive Python method Tree.__len__:
🌐
Byu
cs111.byu.edu › archives › sp23 › disc › disc04
Discussion 4: Tree Recursion, Python Lists :: BYU CS 111
For example, let’s say we want to recursively calculate the nth Virahanka-Fibonacci number, defined as: def virfib(n): if n == 0 or n == 1: return n return virfib(n - 1) + virfib(n - 2) Calling virfib(6) results in the following call structure that looks like an upside-down tree (where f is virfib):
Find elsewhere
🌐
Open Book Project
openbookproject.net › thinkcs › python › english3e › trees.html
27. Trees — How to Think Like a Computer Scientist: Learning with Python 3
The parameter level keeps track of where we are in the tree. By default, it is initially 0. Each time we make a recursive call, we pass level+1 because the child’s level is always one greater than the parent’s. Each item is indented by two spaces per level.
🌐
Arpit Bhayani
arpitbhayani.me › home › blogs › systems internals › visualizing recursion in python with just a decorator
Visualizing Recursion in Python with Just a Decorator
December 13, 2020 - The decorator that wraps the recursive function and prints the recursion tree is as illustrated below. def recviz(fn): """Decorator that pretty prints the recursion tree with args, kwargs, and return values. """ # holds the current recursion level recursion_level = 1 def wrapper(*args, **kwargs): # we register a nonlocal recursion_level so that # it binds with the recursion_level variable.
🌐
FavTutor
favtutor.com › blogs › tree-traversal-python-with-recursion
Tree Traversal in Python (Inorder, Preorder & Postorder)
May 16, 2023 - Here we will recursively call the function preorder to maintain the same process of traversal i.e root -> left -> right if the left child of the original tree has more than one child node and add the answer in the array as shown in the figure below. Lastly, we will traverse the right subtree of the original tree similarly like we did with the left subtree and put the result in the answer array as shown below. Below is the Python code of Preorder Tree Traversal with recursion:
🌐
Runestone Academy
runestone.academy › ns › books › published › pythonds › Recursion › pythondsintro-VisualizingRecursion.html
5.7. Introduction: Visualizing Recursion — Problem Solving with Algorithms and Data Structures
Listing 1 shows how we can use our turtle to generate a fractal tree. Let’s look at the code a bit more closely. You will see that on lines 5 and 7 we are making a recursive call. On line 5 we make the recursive call right after the turtle turns to the right by 20 degrees; this is the right tree mentioned above.
🌐
analyticslink01
analytics-link.com › post › 2018 › 11 › 01 › a-simple-fractal-tree-using-recursion-in-python
A simple Fractal Tree using recursion in Python - analytics-link
November 1, 2018 - Within the tree() function, we draw each extra branch and then recursively call the tree function again and again from within, each time providing a slightly smaller branch length back to the function.
🌐
PyPI
pypi.org › project › recursion-tree-plotter
recursion-tree-plotter · PyPI
January 17, 2021 - A python decorator to generate a visual tree for recursive functions.
🌐
UC Berkeley
inst.eecs.berkeley.edu › ~cs61a › sp23 › lab › lab04
Lab 4: Recursion, Tree Recursion, Python Lists | CS 61A Spring 2023
A tree recursive function is a recursive function that makes more than one call to itself, resulting in a tree-like series of calls.
🌐
PyPI
pypi.org › project › recursion-visualiser
recursion-visualiser · PyPI
A small python package to visualise recursive function on Python. It draws recursion tree
🌐
101 Computing
101computing.net › home › python challenges › recursive tree challenge
Recursive Tree Challenge - 101 Computing
August 30, 2024 - Posted on June 30, 2017 by Administrator Posted in Computer Science, Python - Intermediate, Python Challenges · Look at the code provided below use to draw a tree using a recursive function.
🌐
GitHub
gist.github.com › justbuchanan › 8d76f25e9c68b501556f76c433c22514
recursive tree-building in python · GitHub
recursive tree-building in python. GitHub Gist: instantly share code, notes, and snippets.
🌐
GitHub
github.com › Bishalsarang › Recursion-Tree-Visualizer
GitHub - Bishalsarang/Recursion-Tree-Visualizer: A simple python package that helps to visualise any recursive function by adding a single line of code. · GitHub
Recursion visualiser is a python tool that visualizes recursion tree with animation and draws recursion tree for recursive function. It works with almost any type of recursive function.
Starred by 117 users
Forked by 15 users
Languages: Python 98.8% | Dockerfile 1.2%
🌐
Medium
sathwikgaddi.medium.com › tree-traversal-techniques-in-python-using-recursion-563be2429bd
Tree traversal techniques in Python using Recursion | by Sathwik Gaddi | Medium
April 3, 2021 - The python code for the tree traversal techniques is written below. We create a class Tree that comes with a left child, right child, and data block for each instance. insert_node performs the task of inserting data into the binary tree by holding its properties. We use recursion for performing the in-order, pre-order, and post-order tree traversals.