CKTIS / Python
Recursion
A recursive function solves smaller subproblems and terminates each branch at a base case.
Version: Python 3.14; repository image, production runtime not attested
Syntax
def depth(node):
if not node:
return 0
return 1 + max(depth(child) for child in node)A recursive function solves smaller subproblems and terminates each branch at a base case.
For a tree of lists, an empty node has depth zero and a nonempty one adds one to the maximum child depth. Call stack use grows with depth. A cycle need never reach the base case and can raise RecursionError.
The depths of [] and [[], [[]]] are 0 and 2.
def depth(node):
if not node: return 0
return 1+max(depth(child) for child in node)
assert depth([[],[[]]])==2
loop=[]
loop.append(loop)
try: depth(loop)
except RecursionError: pass
else: raise AssertionError
Examples
def depth(node):
if not node:
return 0
return 1 + max(depth(child) for child in node)
print(depth([]), depth([[], [[]]]))
Result
0 2
The depths of [] and [[], [[]]] are 0 and 2.