I'm trying to understand the recursive implementation of preorder traversal as shown in this link http://interactivepython.org/runestone/static/pythonds/Trees/TreeTraversals.html
def preorder(tree):
if tree:
print(tree.getRootVal())
preorder(tree.getLefChild())
preorder(tree.getRightChild())
I understand how pre-order works, however what I'm flustered with is the recursive implementation shown above. I still can't figure out how after traversing through all the left children the algorithm goes back to the nearest ancestor(parent). I've tried working this out on paper but it still doesn't click.
preorder(tree.getLefChild())
goes through all the left children for the current tree. That method then returns, just like all other methods, then continues on with the parent's right children.
A quick visualization
def preorder(tree):
if tree:
print(tree.getRootVal())
preorder(tree.getLefChild()) # Expand this
preorder(tree.getRightChild())
Becomes...
def preorder(tree):
if tree:
print(tree.getRootVal())
# Entering recursion ...
if (tree.getLefChild()):
print(tree.getLefChild().getRootVal())
preorder(tree.getLefChild().getLefChild()) # And so on...
preorder(tree.getLefChild().getRightChild())
# Exiting recursion...
preorder(tree.getRightChild())
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.