Im using a binary tree described in this book problem solving with algorithms and data structures
class BinaryTree:
def __init__(self,rootObj):
self.key = rootObj
self.leftChild = None
self.rightChild = None
There is already a preorder traversal method defined as follows.
def preorder(tree):
if tree:
print(tree.self.key)
preorder(tree.getLeftChild())
preorder(tree.getRightChild())
I just want to add a return value of the list of nodes visited. So I can do something like
for i in preorder(tree):
etc...
Im having trouble returning a list from a recursive method. The recursion stops as soon as it hits the 'return' I've tried variations using
return [tree.self.key] + preorder()
Or
yield ...
Any ideas?
preorder()is a helper function and not actually a method of theBinaryTreeclass, so calling it a method is a little confusing. 2). Iftreeis an instance ofBinaryTree, thentree.self.keyis wrong. 3). In Python you rarely need getter (or setter) methods, you just access the attributes directly. Eg,preorder(tree.leftChild).