First, the recursive algorithm, easy to understand:
#include <stdio.h>#include<stdlib.h>#include<stdbool.h>typedefstructtreenode{Chardata; structTreeNode *lchild, *Rchild;} TreeNode;voidPreordertraverse (TreeNode *t) { if(NULL = = t)return; printf ("%c",t->data); Preordertraverse (t-lchild); Preordertraverse (t-rchild);}
Then there is the stack simulation recursion:
typedefstructstacknode{TreeNode*pdata; structStacknode *Next;} Stacknode;typedefstructstack{Stacknode*top;} Stack; Stack*init_s () {Stack*pnew = (Stack *)malloc(sizeof(Stack)); Pnew->top =NULL; returnpnew;}voidPush (Stack *s,treenode *p) {Stacknode*pnew = (Stacknode *)malloc(sizeof(Stacknode)); Pnew->pdata =p; Pnew->next = s->top; S->top =pnew;}BOOLEmpty_stack (Stack *s) { returnNULL = = s->top;} TreeNode*pop (Stack *s) {TreeNode*p =NULL; Stacknode*PN =NULL; if( !Empty_stack (s)) {PN= s->top; P= pn->pdata; S->top = pn->Next; Free(PN); } returnp;}voidPreordertraverse (TreeNode *t) { if(NULL = = t)return; TreeNode*p =NULL; Stack*s =init_s (); Push (S,T); while( !Empty_stack (s)) {P=pop (s); if(NULL = =p) { Continue; } printf ("%c",p->data); Push (S,p-rchild); Push (S,p-lchild); }}
Morris traversal algorithm: Space complexity O (1):
Using the concept of the Clue two fork tree (threaded binary trees), the left and right hands of the leaves are used to point to the traversed precursor or successor node.
The algorithm is as follows:
1. Initialize the current node as root
2, if the current node is not empty
A) If the current node has no left child
Access the current node and move the current node to the right child
b) If the current node has left child
Find the right-most node of Zuozi.
If its right pointer is empty, access the current node, point its right pointer to cur, and move to the current node to the left child
If its right pointer is the current node, it resets its right pointer to empty (restore tree) and moves to the right child of the current node
3, repeat the 2nd step
voidPreordertraverse (TreeNode *t) { if(NULL = = t)return; TreeNode*pcur = T, *pre =NULL; while(pcur) {if(pcur->lchild) {Pre= pcur->Lchild; while(Pcur! = Pre->rchild && NULL! = pre->rchild) {Pre= pre->Rchild; } if(Pre->rchild = =pcur) {Pre->rchild =NULL; Pcur= pcur->Rchild; } Else{printf ("%c",pcur->data); Pre->rchild =pcur; Pcur= pcur->Lchild; } } Else{printf ("%c",pcur->data); Pcur= pcur->Rchild; } } }
Main function:
intMain () {TreeNode*t = (TreeNode *)malloc(sizeof(TreeNode)); TreeNode*pnew = (TreeNode *)malloc(sizeof(TreeNode)); T->data ='A'; T->lchild =pnew; T->lchild->data ='B'; T->lchild->lchild =NULL; Pnew= (TreeNode *)malloc(sizeof(TreeNode)); T->lchild->rchild =pnew; T->lchild->rchild->data ='D'; T->lchild->rchild->lchild =NULL; T->lchild->rchild->rchild =NULL; Pnew= (TreeNode *)malloc(sizeof(TreeNode)); T->rchild =pnew; T->rchild->data ='C'; T->rchild->lchild =NULL; T->rchild->rchild =NULL; Preordertraverse (t); printf ("\ n");}
C Pre-sequence traversal binary tree Morris traversal algorithm