树的创建
typedef struct Node
{int data;struct Node *leftchild;struct Node *rightchild;
}*Bitree,BitNode;
void Create(Bitree &T)
{int d;printf("输入结点(按0为空结点):");scanf("%d",&d);if(d!=0){T = (Bitree)malloc(sizeof(BitNode));T->data=d;Create(T->leftchild);Create(T->rightchild);}else{T=NULL;return;}
}
遍历树(递归)
void PreOrder(Bitree &T)
{Bitree D;D=T;if (D){printf("%d", D->data);PreOrder(D->leftchild);PreOrder(D->rightchild);}
}
void InOrder(Bitree &T)
{Bitree D;D=T;if (T){InOrder(D->leftchild);printf("%d", D->data);InOrder(D->rightchild);}}
void PostOrder(Bitree &T)
{Bitree D;D=T; if (T){PostOrder(D->leftchild);PostOrder(D->rightchild);printf("%d", D->data);}
}
非递归遍历
#define MaxSize 100
typedef struct{BitNode *data[MaxSize];int top;
}SqStack;
void InitStack(SqStack &S){S.top = -1;
}
bool StackEmpty(SqStack S){if(S.top==-1) return true;else return false;
}
void Push(SqStack &S, BitNode *x){if(S.top==MaxSize-1) return;S.top = S.top+1;S.data[S.top]=x;
}
BitNode* Pop(SqStack &S){if(S.top==-1) return NULL;BitNode *x;x= S.data[S.top];S.top = S.top-1; return x;
}
void InOrder2(Bitree &T){SqStack S;InitStack(S);Bitree P=T;while(P||!StackEmpty(S)){if(P){Push(S,P);P=P->leftchild;} else{P=Pop(S);printf("%d",P->data);P=P->rightchild;}}
}void PreOrder2(Bitree &T){SqStack S;InitStack(S);Bitree P=T;while(P||!StackEmpty(S)){if(P){printf("%d",P->data);Push(S,P);P=P->leftchild;} else{P=Pop(S);P=P->rightchild; }}
}
层次遍历
#define MaxSize 100
typedef struct{int front,rear;BitNode *data[MaxSize];
}SqQueue;
void InitQueue(SqQueue &Q){Q.front=Q.rear=0;
}
bool QueueEmpty(SqQueue Q){if(Q.front==Q.rear) return true;else return false;
}
bool EnQueue(SqQueue &Q,BitNode *x){if((Q.rear+1)%MaxSize==Q.front){return false; }Q.data[Q.rear]=x;Q.rear = (Q.rear+1)%MaxSize;return true;
}
BitNode* DeQueue(SqQueue &Q){if(Q.front==Q.rear) return NULL;BitNode *x;x = Q.data[Q.front];Q.front=(Q.front+1)%MaxSize;return x;
}
void LevelOrder(Bitree &T){SqQueue Q;InitQueue(Q);Bitree P;EnQueue(Q,T);while(!QueueEmpty(Q)){P=DeQueue(Q);printf("%d ",P->data);if(P->leftchild!=NULL)EnQueue(Q,P->leftchild);if(P->rightchild!=NULL)EnQueue(Q,P->rightchild);}
}
主函数
int main(){Bitree T;Create(T);printf("前序遍历:");PreOrder(T);printf("\n");printf("中序遍历:");InOrder(T);printf("\n");printf("后序遍历:");PostOrder(T);printf("\n");printf("中序遍历(非):");InOrder2(T);printf("\n");printf("前序遍历(非):"); PreOrder2(T);printf("\n");printf("层次遍历:");LevelOrder(T);return 0;
}