In the non -recursive traversal traversing of the prelude, medium, and post -order, the post -order is the most troublesome. If you only retain the pointer of the pointing node in the stack, it is not enough. Some additional information must be stored in the stack.
There are many methods. Only one is given here, first define the data structure of the stack node
Copy code code as follows:
TypeDef Struct {node * p; int RVISITED;} Snode // node is the node structure of the binary tree. RVISITED == 1 means that the right node of the node pointed by P has been accessed.
LastORDERTRAVERSE (Bitree Bt) {
// First, start from the root node, go to the bottom left, go to the head, and enter each node on the path into the stack.
p = bt;
While (bt)
push (bt, 0); // push to the stack two information, one is the node pointer, and the other is whether the right node has been accessed
bt = bt.lchild;
}
// Then enter the cycle body
While (! Stack.empty ()) {// As long as the stack is not empty
sn = stack.gettop (); // Sn is the top node of the stack
// Note, any node n, as long as he has a left child, after N enter the stack, the left child of N must follow the stack (this is reflected in the second half of the algorithm), so when we get the stack When the top element, you can be sure that this element either has no left child or his left child has been accessed, so at this time we don't care about its left child, we only care about its right child.
// If the right child has been accessed, or the element does not have the right child, the definition of the post -sequential traversal can be traveled. At this time, the VISIT node is available.
if (! SN.P.RCHILD || SN.RVISITED) {{
p = pop ();
visit (p);
}
Else // If its right child exists and RVISITED is 0, it means that the right child who has not moved has not been moved before, so he will deal with his right child.
{{
// At this time, we have to go to the bottom left from the node of the right child until the end, and to put all the nodes on this path into the stack.
// Of course, set the RVISITED of the node to 1 before entering the stack, because the stack of the right child means that its right child will be accessed before it (this is well understood because we always follow from from the observation Take the element of the stack for visit). It can be seen that when the element is on the top of the stack, the right child must be passed by Visit, so the RVISITED can be set to 1 here.
sn.rvisited = 1;
// Go to the end to the bottom left and put all elements on the path into the stack
p = sn.p.rchild;
While (p! = 0) {
push (p, 0);
p = p.LChild;
}
} // This cycle has ended. We don't have to control the nodes that have just entered the stack. The next round of cycle will take care of these nodes well.
}
}