简体   繁体   English

二叉树遍历 - 预购 - 访问父节点

[英]Binary Tree Traversal - Preorder - visit to parent

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我正在尝试了解前序遍历的递归实现,如此链接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. preorder(tree.getLefChild())当前树的所有左孩子。 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())  

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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