本文共 1341 字,大约阅读时间需要 4 分钟。
一、树
二、二叉树的遍历 1、先序遍历 A、递归void PreOrder(BiTree T){ if(T!=NULL){ visit(T); PreOrder(T->lchild); PreOrder(T->rchild); }}
B、非递归
void PreOrder(BiTree T){ InitStack(S);BiTree p=T; while(p||!IsEmpty(S)){ if(P){ visit(p);Push(S,p); p=p->lchild; }else{ Pop(S,p); p=p->rchild; } }}
2、中序遍历
A、递归void InOrder(BiTree T){ if(T!=NULL){ PreOrder(T->lchild); visit(T); PreOrder(T->rchild); }}
B非递归
void InOrder(BiTree T){ InitStack(S);BiTree p=T; while(p||!IsEmpty(S)){ if(P){ Push(S,p); p=p->lchild; }else{ Pop(S,p); visit(p); p=p->rchild; } }}
3、后序遍历
A、递归void PostOrder(BiTree T){ if(T!=NULL){ PreOrder(T->lchild); PreOrder(T->rchild); visit(T); }}
B、非递归
void PostOrder(BiTree T){ InitStack(S);BiTree p=T; r=NULL; while(p||!IsEmpty(S)){ if(P){ Push(S,p); p=p->lchild; }else{ GetTop(S,p); if(p->rchild&&p->rchild!=r){ p=p->rchild; push(S,p); p=p->lchild; }else{ Pop(S,p); visit(p->data); r=p; p=NULL; } } }}
4、层次遍历
void LevelOrder(BiTree T){ InitQueue(Q); BiTree p; Enqueue(Q,T); while(!IsEmpty(Q)) { Dequeue(Q,p); visit(p); if(p->lchild!=NULL) Enqueue(Q,p->lchild); if(p->echild!=NULL) Enqueue(Q,p->rchild); } }
5、由遍历序列构造二叉树
由二叉树的先序遍历和中序遍历可以唯一地确定一颗二叉树。 后序和中序可以唯一确定。 层序中序唯一确定。 先序后序不可以确定。转载地址:http://xwgwi.baihongyu.com/