I am building a program to build and explore binary trees in native Python.
I defined a Node class and a depth()
method which aims to get the depth of the given node recursively. This works as expected when I want to print the depth, but it returns None
class Node():
def __init__(self, n, g=None, d=None, parent=None):
self.parent = parent
self.n = n
self.g = g
self.d = d
def addNodes(self, g=None, d=None):
# some code to add nodes
def printTree(self, indent = "") :
# some code to pretty print the tree
def depth(self, count=0):
if self.parent != None :
count += 1
self.parent.depth(count)
else :
print(f"Printing count inside the function : {count}")
return count
def treeExemple():
# creating a simple tree
root = Node("root")
a, b = root.addNodes("a", "b")
c, d = a.addNodes("c", "d")
e, f = b.addNodes("e", "f")
i = e.addNodes(d="i")
j, k = f.addNodes("j", "k")
# printing it to check everything is right
root.printTree()
# trying to print the depth of a particular node
depthK = k.depth()
print(f"Printing count outside the function : {depthK}")
if __name__ == '__main__':
treeExemple()
Running the program :
+-root
| +-a
| | +-c
| | +-d
| +-b
| | +-e
| | | +-i
| | +-f
| | | +-j
| | | +-k
Printing count inside the function : 3
Printing count outside the function : None
Since it's the first time I dive into oop, I might be missing something really obvious. Any help will be greatly appreciated !