简体   繁体   中英

Walking a BST in Python 3

Could anybody explain how it is that the computer ever gets to walkTree(tree['right']) ? I believe that the function keeps calling itself until None and then recursively pops off all of the "left" stacks and printing them, but when the function calls walkTree(tree['right']) , what is the computer doing when it passes by walkTree(tree['left']) again?

def walkTree(tree):
    if tree == None:
        return None
    walkTree(tree['left']
    print(tree['data'])
    walkTree(tree['right'])

BST is a recursive data structure. When you're calling the function with the 'left' value, it is going to the left half of the BST. Then this recurses and continues till it reaches the leftmost node in the tree. Then it starts travelling back up and goes to the immediate right subtree of it's parent (the parent of the leftmost node). Then again the same process continues and it visits the left subtrees first and proceeds in that fashion. When it finally reaches the root of the whole tree while travelling back up (after ALL nodes in the left half is visited) it's time to visit the right subtree. Then again it goes to the left subtree of that root (right of the absolute root) if any is present. This left subtree is not the left subtree of the main tree but that of the right node of the main root.

Your code basically would print the values in the entire BST in ascending order. Also, I think it should be

if tree == None:
    return

It sounds like you do not understand how the call stack works. Take a simple tree:

   2
  / \
 1   3

The call stack would look like (using indentation to indicate level in the call stack):

walkTree(tree)
    walkTree(left)
        walkTree(left)
            return
        print(1)
        walkTree(right)
            return
        return (implicit)
    print(2)
    walkTree(right)
        walkTree(left)
            return
        print(3)
        walkTree(right)
            return
        return (implicit)
    return (implicit)

A return at the bottom of the call stack only returns to the call stack one higher, not all the way to the top.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM