Explain Morris inorder tree traversal without using stacks or recursion

前端 未结 8 1143
别跟我提以往
别跟我提以往 2020-11-27 09:15

Can someone please help me understand the following Morris inorder tree traversal algorithm without using stacks or recursion ? I was trying to understand how it works, but

8条回答
  •  北荒
    北荒 (楼主)
    2020-11-27 09:22

    I hope the pseudo-code below is more revealing:

    node = root
    while node != null
        if node.left == null
            visit the node
            node = node.right
        else
            let pred_node be the inorder predecessor of node
            if pred_node.right == null /* create threading in the binary tree */
                pred_node.right = node
                node = node.left
            else         /* remove threading from the binary tree */
                pred_node.right = null 
                visit the node
                node = node.right
    

    Referring to the C++ code in the question, the inner while loop finds the in-order predecessor of the current node. In a standard binary tree, the right child of the predecessor must be null, while in the threaded version the right child must point to the current node. If the right child is null, it is set to the current node, effectively creating the threading, which is used as a returning point that would otherwise have to be on stored, usually on a stack. If the right child is not null, then the algorithm makes sure that the original tree is restored, and then continues traversal in the right subtree (in this case it is known that the left subtree was visited).

提交回复
热议问题