title: Design of a non-recursive algorithm for the execution of sequential traversal
Answer:
Analysis:
1, the use of stack simulation recursive call process, that is, you can achieve the middle sequence traversal
2, increase the pointer field in the node, so that the pointer field points to the parent node, by iterating to achieve the middle sequence traversal
Non-recursive algorithm:
Stack simulation algorithm version one:
// inorder TRAVERASL void inorder (Searchtree T) { Stack S; while (T! = NULL | |! s.empty ()) { if (t! = NULL) { s.push (t) ; = T-> left; } Else { = s.pop (); Visit (T); = T-> Right;}} }
Note: This algorithm is implemented using depth-first search techniques, which are visit when backtracking.
Stack simulation algorithm version two:
//inorder TRAVERASL version2.0voidinorder (Searchtree T) {Stack S; if(T! =NULL) S.push (T); T->childpushed =false; while( !S.empty ()) {Searchtree Tnode=S.pop (); if(tnode->childpushed) { //if the identity bit is true, it means that the left and right subtrees are already in the stack, so you need to access that node now.Visit (tnode); } Else { //The left and right sub-tree has not yet entered the stack, then, in turn , the node if(Tnode->right! =NULL) { //both left and right subtrees are set to Falsetnode->right->childpushed =false; S.push (Tnode-Right ); } tnode->childpushed =true;//root node flag bit is trueS.push (tnode); if(Tnode->left! =NULL) {Tnode->left->childpushed =false; S.push (Tnode-Left ); } } }}
Note: The algorithm uses the width-first search technique to mark whether the Childpushed flag can be visit.
Parent Node Implementation version:
voidinorder (Searchtree T) { while(T! =NULL) { while(T->left! = NULL &&!) T->left->visited) T= t->Left ; if( ! T->visited) {Visit (T); T->visited =true; } if(T->right! = NULL &&!) T->right->visited) T= t->Right ; ElseT= t->Parent; }}
Note: Using this method requires adding a pointer field to the parent node, which will have some difficulty in the achievement
Algorithm time complexity Analysis: O (N)
Introduction to Algorithms 12.1-3