//3后序遍历二叉树的非递归算法
void PostOrder2(BiTree T)
{
Initstack(s);
BiTree p=T;
r=NULL;
while(p||!Isempty(s))
{
if(p!=NULL)
{
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 InvertLevel(Bitree bt)
{
Stack s;
Queue q;
if(bt!=NULL)
{
Initstack(s);
Initqueue(q);
enqueue(q,bt);
while(Isempty(q)==false)
{
dequeue(q,p);
push(s,p);
if(p->lchild)
enqueue(q,p->lchild);
if(p->rchild)
enqueue(q,p->rchild);
}
while(Isempty(s)==false)
{
pop(s,p);
visit(p->data);
}
}
}
//5高度计算
int btdepth(Bitree T)
{
if(!T)
return 0;
int front=-1,rear=-1;
int last=0,level=0;
BiTree q[maxsize];
q[++rear]=T;
BiTree p;
while(front<rear)
{
p=q[++front];
if(p->lchild)
q[++rear]=p->lchild;
if(p->rchild)
q[++rear]=p->rchild;
if(front==last)
{
level++;
last=front;
}
}
return level;
}
//5-2用非递归实现
int btdepth2(BiTree T)
{
if(T==NULL)
return 0;
ldep=btdepth2(T->lchild);
rdep=btdepth2(T->rchild);
if(ldep>rdep)
return ldep+1;
else
return rdep+1;
}
//6 建立二叉树的二叉链表
l1=l1=1;
h1=h2=n;
BiTree PreInCreate(elemtype A[],elemtype B[],int l1,int h1,int l2,int h2)
{
root=(BiTNode*)malloc(sizeof(BiTNode));
root->data=A[l1];
for(int i=l2;B[i]!=root->data;i++);
llen=i-l2;
rlen=h2-i;
if(llen)
root->lchild=PreInCreate(A,B,l1+1,l1+llen,l2,l2+rlen-1);
else
root->lchild=NULL;
if(rlen)
root->rchild=PreInCreate(A,B,h1-rlen+1,h1,h2-rlen+1,l2,h2);
else
root->lchild=NULL;
return 0;
}