Simple algorithms for traversing a tree without an auxiliary stack

Simple algorithms for traversing a tree without an auxiliary stack

INFCIRMATIQN PPOC’ESSIPlrr,: ETTERS 2 Cl 97.4) 143- 14.5. NORTH-HOLLAND PUBLISHING COMPANY Barry DWYER lbwgemsnt Ssrpbccs,S.A. !nstitute of Techndogy...

526KB Sizes 0 Downloads 41 Views

INFCIRMATIQN PPOC’ESSIPlrr,: ETTERS 2 Cl 97.4) 143- 14.5. NORTH-HOLLAND PUBLISHING COMPANY

Barry DWYER lbwgemsnt Ssrpbccs,S.A. !nstitute of Techndogy, NorthTmce, Adelaide, South Ausmli~ 5000, Austrnlia Received 15 December1973 data structures

analysis of aigwithms

1.Intro4hlction

2. Algorithm T. Threefold travme

In problem 2 1, section 2.3.1, Knuth [l] posed the problem of uaversing a binary tree without the use of an auxihary stack. Siklossy [3] compared K~uth’s solution to this problem with his own algorithms, and Robsoa (21 has presented a third amroach.. The notation used here follows the previous authors except for the nomenclature of the orders of traversal, In the 2nd editian of his %ook,Knutb has adoptexi the terms preordei, inorder (or symmetric order) and postorder rather than (respectively) preorder, postorder and endorder. The three o,tders are defmed recursively as follows:

A surprisingly simple algorithm can be used to traverse a binary tree in triple order. Before consid= ering it in detail, we must defme the computer representation used. Each node of thle tree has two address folds LLDK and RLlNK, which point to the roots of the left and right subtrees. FW convenience in th.e

Rder

l.Visitth&?! root node; 2. Travel t&e left sul?treq 3. Travelsb the right subtree.

Intmler Postorder 1. Traverse the 1. Traverse the left subtree; left subtree; 2, Visit the 2. Traverse the right subtrw, root node; 3. Traverse the 3. Visit the right subtree. root node.

Each of thesu orders may be obtained from the’following order by deleting two of the steps 1) 3 or 5. Wple arder 1. Visit the root node (preorder); 2. Travme the left subtree; 3. Visit the root node (inorder); 4, Trave~rsethe right subtree; 5. Visit like root node (postorder).

following algorithm, the links poiint reflexively to the node itself when the subtree is empty. (This is in zontrast to the usual representation, jlrvhere such Unks have a special value, usuajliy zero.)t The trze is motc:r at ROOT. Algorithm T traverses the tree in triple order and visits each node exactly three times. During the algorithm, PRES points to the present node and PREV to the previously visited node. NEXT points to the next node to be visited. A&otithm T fl%mqftM mvem] Tl . [InitW~e.] Set PRES + ROOT, PREV + A. T2. (Compiete? ] If PRES :* A, terminate the algorithm. T3. [Triple-order visit.] Visit NODE(PRES). T4. [Turn right.] Set NEXT + LLlMC(PRES), LLINK(PRES) + RLINK(PRES), RLINlC(PRES) + PREV, PREV + PRES, PRES,+ NEXT and go i;o step 2. a Note that this algorithm is iI simp.leiteration with only one test. In traversing ,the ‘iree,IPRESdescribes a path which always\ turns right at each node. At the same tizn\\cthe algorithm rotate!: the ilis of the node anticlockwise so that the next t)me the node is visited it is from be same d!irection rel;ltive I:Oits MS. After

>g~vi&~ the node

isrotated to its or@nal otientation

#.*me of the lemma, after the tree is traversed, T2 is reached with R.ES = A and the algorithm tertinates. This proves the algorithm, except for a null tree. The null case can be handled by choosing ROOT = A.

‘J‘herefk&ve linlcscause the path of PRES to reserve S;rrrmsdhteIywhenit starts toward a null subtree. In Algorithm T is able to operate correctly the Irblindly).

4. Number laf skps in Algodtbm T Since the algorithm traverses the tree and visits each node exactly three times, step T3 must be executed 3n times, where His the number of nodes in the tree. Step Tl is executed once, because there is no way of returning to step Tl.Wng ICirchhoff’s lawi step T4 is executed 3n and step T2 3n + 1 times.

we Uprove tfhefollowing lemma by recurIf step T2 is begun with PRES @nting uct node Sni& @inal state, then after traversingthat &tree step T2 isagain reached withal1 links subtree res?ored to their original values, and with tkvalues of PRES and PREV exchanged. ti &, & Lo and R, be the values of PRES, PREV, LLINK@!RES),and RLINIC(PRES)when the node initiaily enoeuntered at step T2. Since iVOis the ion of a node, PIES + A, so step T3 is reached

5. VariantsofAlgorithm T

step

T4, we have PRlB = t,, PREV=&,

Algorithm T cannot distirsguishbetween going left, .orup, nor b&we&t Reorder, inorder &ti postorder _visi@In or@ to do that, some additional mecharii@ Is‘needed, Tre& are ofaen stored 50 that the sons of a node have higherfocatio& :&arkthe node itself. It can be seen in the above pkof that POis either the tither of A$&or A. W&can th&efore-guaranteepo
* .

A@yr@hm U+fUi&ersal

trwersel

Uf . &Maliz~.] (Same as Tl.) U2.. icomplete ?] (Same.as T2 .) U3. [Visit,] If traversing in preorder and PRRV < . C PI@!&visit lWDI5(pRIEis).Xftravqsing in inorder,and RLINR(PRI?S)
thc,@+W@n for traversing time st+‘T2 i# reMred. By

In this restricted case, the nodes do not require additional TAG bits. Asecond method is to include a module 3 counter &Iertcthnode to dMinguish the first, second and third visit&A convenient impiementation is to provide two tigs WAG and RTAG at each node, perhaps using the sign bits of LLINKand RLINK. This variation is shown in Algoti&m M. LTAG and RTAG are b& initially +.

B. Dwyer, Tmversing u tree without an auxiltiry stack

Algorithm Rf ; 3 traverse] Ml. [Initialize.] (Same as Tl.) M2. [Complete ?] (&me as T2.) M3. [Visit.] IF traversing in preorder and LTAG(PREs) = t, and RTAG(PRES) = t, visit NODE(PRES). If traversing in imorder and RTAG(PRES) = -,$ visit NODE(PRES). If traversing in postorder and LTAG(PRES) = -, visit NODE (PRES). M4. [Count visits.] If LTAG(PRES) = + and RTAG(PRI%)= t, set PTAG+ - utherwke selt PTAG + +. Then set LTAG(PRES) + RTAG(PRES),RTAG(PRES)+-PTAG. M5. [Turn right.] (Sameas T4.) LTAGand RTAGconstitute a module 3 counter with vrilu~ ++, t- and -t. Alternatively Algorithm M can be regarded as a variant of Algorithm U where POis taged by a -, instead of its distinctive value. A third f,rossibilityis to include a single variable DIR which indicates the direction from which a node is emtezed.When DIR = 1, the node is enteredfr: :a above, when DIR = 2 from the left and when DIR = = 3 from the right. DIR has the value 1 for preorder visits, 2 for inorderand 3 for postorder. ICeepIngtrackof DIR is not difficult except when a node is ent -red from the right. The next node enteredwiIIbe the fatherof that node, but it may be enteredfrom its feft or rightdependingon whether this node is a left or rightson. Each node therefare must igclude a bit, RSON,hating the value 1 ifit is rightson, otherwise 0. AigorithmD incorporatesthis technique. AlgorithmD [Directian-sensitivetraverse] 81. [mitialize.] Set PRES+ ROOT, PREV + A, DIR+1. D2. [CompIete ?] (Same as T2.} D3, [Vi&.] If traversingin preorderand DIR = 1, viait NODE(PRES). If traversingin inorderand DIR = 2, visit NODE(lYUj. If traveaingin postorderand DIR = 3, visit NODE(PRIB). D4. [Re-otient.] If LIJNK(PRES)= PRES, set DIR ++ DIR t 1 and go to step DS. Otherwise if DIR =

145

= 3, set DIR + RSON(PRES) + 2; otherwise set DIR+-. D5. [Turn right.] (Same as ‘14.)m (This algorithm :. f&ted t c)~iklossy’s Algorithm 2 (BITFRIX), excep + 6~ dtk.n3t rotate :he links. Step W2, W4 and W6 of that a@orithm correspond to step D3 with DIR = 1,2 and 3 ) Finally, although t!le convention of representing null links reflexively is a convenient one, these algolithms can 6e modified to the usual convention that a special value, A, is used. In algorithm T, we must replace A by another constant (distinct from all node addresses) in steps Tl and T2, then replace T4 by: T4a. [Turn right.] Set NEI‘;T+ LLINK::PRES), LLINK(PRES) + RLINK(‘PRES).lif PREV = = PRES, set RLINK(PRES) + A, otherwise set RLINK(PRES) + PREV. If NEXT # A set PRES * NEXT. Go to step T2. SimiIar amendments to the other algorithms will make them work correctly too under these ground rcles. ’ The idea embodied in A!gorithm T applies also to ternary Ereesor trees with a variable number of Elks per node.

Note added in proof It has just come to the author’s attention that G. Lindstrom has independently published algorithms strongly related to those of this paper, in Inform. Proc. L&t. 2 (1973) 47-51.

References

111D.E. Knuth, 77~ Art of Computerfbgmmming Vol. 1, Addison-Wesley, Reading, Massachusetts, 1968 (2nd Zd. 1973). (21 I.M. Robson, Inform. Proc. Lett. 2 (19’7?) 12. (31 L. Silclossy, Inform. Proc. L&t. 1 (1972) 149.