声明
这些代码都不是直接搬过去马上能用的代码,只是学习思路,代码风格的。只给出了函数主体,并不是一个完整的c/c++文件。
递归前序遍历
void preOrder(Tree T)
{
if(T){
visit(T);
preOrder(T->lchild);
preOrder(T->rchild);
}
}
递归中序遍历
void inOrder(Tree T)
{
if(T){
preOrder(T->lchild);
visit(T);
preOrder(T->rchild);
}
}
递归后序遍历
void preOrder(Tree T)
{
if(T){
preOrder(T->lchild);
preOrder(T->rchild);
visit(T);
}
}
非递归前序遍历
void preOrder2(Tree T){
InitStack(S);
Tree p=T;
while(p!=NULL||!empty(S)){
if(p){
visit(p);
push(S,p);
p=p->lchild;
}
else{
pop(S,p);
p=p->rchild;
}
}
}
非递归中序遍历
void inOrder2(Tree T){
InitStack(S);
Tree p=T;
while(p!=NULL||!empty(S)){
if(p){
push(S,p);
p=p->lchild;
}
else{
pop(S,p);
visit(p);
p=p->rchild;
}
}
}
非递归后序遍历
void preOrder2(Tree T){
InitStack(S);
Tree p=T;
Tree r=NULL;//指向最近访问过的结点
while(p!=NULL||!empty(S)){
if(p){
push(S,p);
p=p->lchild;
}
else{
GetTop(S,p);
if(p->rchild&&r!=p->rchild){
p->rchild;
push(S,p);
p=p->lchild;
}
else{
pop(S,p);
visit(p);
r=p;
p=NULL;//不赋值NULL则下一个循环判断又把这个结点压入栈中,这样就无限循环了。
}
}
}
}
层次遍历:自上而下,从左往右
void levelOrder1(Tree T)
{
Queue Q;
initQuque(Q);
Tree p=T;
if(T==NULL)
return;//空树判断,空树则直接返回
inQueue(Q,p);//入队
while(!empty(Q)){
deQueue(Q,p);//出队
visit(p);
if(p->lchild)
inQueue(Q,p->lchild);
if(p->rchild)
inQueue(Q,p->rchild);
}
}
层次遍历:自上而下,从右往左
void levelOrder2(Tree T)
{
Queue Q;
initQuque(Q);
Tree p=T;
if(T==NULL)
return;//空树判断,空树则直接返回
inQueue(Q,p);//入队
while(!empty(Q)){
deQueue(Q,p);//出队
visit(p);
if(p->rchild)
inQueue(Q,p->rchild);
if(p->lchild)
inQueue(Q,p->lchild);
}
}
层序遍历:自下而上,从左往右
其实这个就是自上而下,从右到做的方式,在每次出队列后压入栈中,对栈中元素从栈顶访问到栈空即可。
void levelOrder3(Tree T)
{
Stack S;
Queue Q;
initStack(S);
initQuque(Q);
Tree p=T;
if(T==NULL)
return;//空树判断,空树则直接返回
inQueue(Q,p);//入队
while(!empty(Q)){
deQueue(Q,p);//出队
push(S,p);
if(p->rchild)
inQueue(Q,p->rchild);
if(p->lchild)
inQueue(Q,p->lchild);
}
while(!empty(S)){
pop(S,p);
visit(p);
}
}
层序遍历:自下而上从右到左
这个也是同理,就是自上而下,从左到右的方式,每个结点出队列后被压入栈中,然后对栈中元素访问。
void levelOrder4(Tree T)
{
Stack S;
Queue Q;
initStack(S);
initQuque(Q);
if(T==NULL)
return;//空树判断,空树则直接返回
Tree p=T;
inQueue(Q,p);//入队
while(!empty(Q)){
deQueue(Q,p);//出队
push(S,p);
if(p->lchild)
inQueue(Q,p->lchild);
if(p->rchild)
inQueue(Q,p->rchild);
}
while(!empty(S)){
pop(S,p);
visit(p);
}
}