The non-recursive creation of a two-fork tree in sequence , using the queue (can be FIFO feature) to store the address of the visited node element.
Initialization: front=rear=-1;
Each node element is stored rear+1, using rear%2==0 to make front+1 enter indicates that the node input is complete.
1 //Structural Body2 structNode {3 Chardata;4Node *Lchild;5Node *Rchild;6 };7 /*private construction method in class tree Node * Create ()8 Note: This method needs to be entered in a sequence traversal mode9 */TenNode *tree::create () { OneNode * Queue[max];//Max is the maximum number of storage node data A CharCh[max]; - intFront =-1, rear =-1, i =0; -Node * root = NULL, * tem =NULL; the -Cin>> ch;//Input Node Data - while(Ch[i]! =' /') { - //checks whether an input character is empty or a value, and puts it in a queue + if(Ch[i]! ='#') {//is not equal to NULL, is an element, creates a node and holds the data, and puts its TEM address in the queue . -TEM =NewNode (); +Tem->data =Ch[i]; AQueue[++rear] =tem; at}Else{//the input is empty, and a null is also placed in the queue -TEM =NULL; -Queue[++rear] =tem; - } - //set the node's left and right children - if(Rear = =0) {//If rear is 0, the expression is the first element, that is, the root node has only one time to execute the inner statement. inroot = tem;//at this point the root points to the TEM, and Queue[0] is also the address of the TEM, so root indirectly points to the queue[0], the following code constructs the left and right child tree, Queue[0] is the root node, that is, to build the current first created by the TEM address is the root node of the two-fork tree, so Root points to TEM (Note: This line of code executes only once) -}Else { to if(queue[front+1]!=null && tem!=null) {//not for the root node front+1 point is the team head, so Judge team head is not empty and TEM is not empty, that contains left and right (because empty, then no children) + //because according to the queue storage mode, outside the root node, subscript is an odd number of left children, even the right child - if(rear%2==1) {//Odd: Left child thequeue[front+1]->lchild =tem; *}Else{//I: Right child $queue[front+1]->rchild = tem;//Note: When executing this statement, the right child that has the current TEM node as a nodePanax Notoginsengfront++;//front++, said the current team head of the right children are set up, stating that the team head elements around the children are finished, the next node set left and right children, then let the current team head out of the team, the next node set as Team head - } the } + } Ai++;//character array subscript 1, set next character element the } + returnRoot; -}
The diagram is the first time that the right child is built:
Non-recursive creation of two-fork tree (c + + queue)