I have question about postorder traversal.
The code from online is:
def postorder(tree):
if tree != None:
postorder(tree.getLeftChild())
postorder(tree.getRightChild())
print(tree.getRootVal())
i am not sure how this will ever reach the print line. Here it will keep going left until there is no left so we never get past
postorder(tree.getLeftChild())
when there is no left this line:
if tree != None:
wont be met and it will not print.
Consider a leaf, which has no children. Line by line:
if tree != None: # isn't None, so continue
postorder(tree.getLeftChild()) # will call postorder(None), which won't pass if
postorder(tree.getRightChild()) # will call postorder(None), which won't pass if
print(tree.getRootVal()) # will print
So it will reach the very bottom of the tree, and invoke the print of leaves there. Then it will recurse back up. As you noted, left subtrees will be printing before right subtrees.
Specifically about "never get past", it will. Let's consider this line, again for a leaf:
postorder(tree.getLeftChild())
For a leaf getLeftChild
returns None. So that line effectively means
postorder(None)
And the if
statement means that the method will just do nothing and return if None is passed.
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.