简体   繁体   English

迭代二叉树中序遍历python

[英]Iterative binary tree inorder traversal python

In this LeetCode Q/A an answer w/o any inline comments demonstrates how to accomplish iterative in-order binary tree traversal.这个LeetCode Q/A 中,一个没有任何内联注释的答案演示了如何完成迭代的有序二叉树遍历。

class Solution:
    def inorderTraversal(self, root: TreeNode) -> List[int]:
        traversal = []

        node = root
        stack = []
        while node or stack:
            if node:
                stack.append(node)
                node = node.left
            else:
                node = stack.pop()
                traversal.append(node.val)
                node = node.right
                
        return traversal

Why does this work?为什么这行得通? I'm primarily confused by the if node statement, which always moves to the left child.我主要对if node语句感到困惑,它总是移动到左孩子。 The else statement must satisfy the conditions that node does not exist but stack does exist, and this is really perplexing to me. else语句必须满足节点不存在但栈存在的条件,这让我很困惑。

I'd like to understand it such that I could tweak code to perform pre or post order traversal but not understanding why this code functions, that's a bride too far.我想理解它,以便我可以调整代码以执行订单前或订单后遍历,但不明白为什么这个代码会起作用,这太过分了。

At the start of every iteration of the loop, node represents the root of a subtree that has not yet been visited (at all).在循环的每次迭代开始时, node表示尚未访问(完全)的子树的根。

By definition of "in-order traversal", we should first traverse the left subtree of a node, before anything else.根据“有序遍历”的定义,我们应该首先遍历节点的左子树,然后再进行其他操作。 So that is why -- when we have the root of an unvisited subtree -- we should go left .所以这就是为什么——当我们有一个未访问的子树的根时——我们应该向左走 At the same time, we take note of the this node, because at some point we will be ready with that left subtree, and then we must be able to find back this node and actually visit it.同时,我们注意到这个节点,因为在某个时候我们将准备好左子树,然后我们必须能够找到这个节点并实际访问它。 That is why we push the node on the stack before going left.这就是为什么我们在离开之前将节点压入堆栈。

When the root of an unvisited subtree has no left child, then node will obviously become None and so in the next iteration we arrive in the else case.当未访问的子树的根没有左孩子时, node显然会变为None ,因此在下一次迭代中,我们到达else情况。 There we pop again the parent node from the stack.在那里,我们再次从堆栈中弹出父节点。 Now the first thing to do is visit that root ( append ), and after that we must visit its right subtree, which will be initiated in the next iteration of the loop.现在要做的第一件事是访问那个根( append ),然后我们必须访问它的子树,这将在循环的下一次迭代中启动。

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

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