题目:给定一棵二叉树,假设从二叉树的右侧观察它,将观察的结点按照从上到下输出
思想:利用层次遍历,从上到下依次输出这一层的最后一个元素即可,注意将层数与结点一起入队
代码展示:
void fromTheSide(BiTree T,SqQueue &Q)
{
if(T==NULL)
{
return;
}
EnQueue(Q,T,1);
while(QueueEmpty(Q)==0)
{
BiTree x;
int l;
DeQueue(Q,x,l);
if(Q.level[Q.front]!=l || QueueEmpty(Q)==1)
{
printf("%d ",x->data);
}
if(x->lchild!=NULL)
{
int k = l+1;
EnQueue(Q,x->lchild,k);
}
if(x->rchild!=NULL)
{
int m = l+1;
EnQueue(Q,x->rchild,m);
}
}
}