This article mainly introduces the two-fork tree of the non recursive sequence traversal algorithm example, the need for friends can refer to the following
Before the preface, in order, after the sequence of the non recursive traversal, to count the most troublesome, if only in the stack to keep the pointer to the node, it is not enough, there must be some additional information stored in the stack. There are a lot of ways, here just one, first define the data structure of the stack node code as follows: TypeDef struct{node * p; int rvisited;} The Snode//node is the node structure of the two-fork tree, and the right node of the node that the Rvisited==1 points to is already accessed. Lastordertraverse (Bitree bt) {//First, start at the root node, go to the bottom left, go straight to the end, put each node on the path onto the stack. p = BT; while (BT) {push (BT, 0),//push to the stack of two information, one is the node pointer, whether its right node has been visited BT = Bt.lchild; //Then enter the loop 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 left children, then after n into the stack, N of the left child must also follow the stack (this is reflected in the algorithm The second half, so when we get to the top of the stack, we can be sure that the element either has no left child or that the left child has been visited, so we don't care about the left child, we only care about the right child. //Jochi right child has been visited, or the element has no right child, by the definition of the subsequent traversal, at this point can visit this node. if (!sn.p.rchild | | sn.rvisited) {p = pop (); Visit (p); else//If the right child is present and rvisited is 0, the right child has not been moved before, so go and deal with the right child. { //At this time we want to start from the right child node began to go down to the left, until the end, the path of all the nodes into the stack. Of course, the rvisited of the node is set to 1 before entering the stack, because the right child's stack means that its right child must be accessed before it (which is well understood because we always take the element from the top of the stack for visit). So the next time the element is on top of the stack, the right child must have been visit, soHere you can set the rvisited to 1. sn.rvisited = 1; //To the bottom left, all elements of the path into the stack p = sn.p.rchild; while (P!= 0) {push (P, 0); p = p.lchild; }//this round of loops is over, we don't have to worry about the nodes in the stack, the next round of loops will take care of these nodes very well. }}