题目描述,层序从左到右打印二叉树。终于遇到简单一点的了,之前写过,剑指offer20-21有点难。
分析:层序遍历二叉树实际上很简单,就是用一个队列存根节点,进入循环,直到队列为空结束,然后出队,打印根节点,如果队列的左节点不为空,进队,右节点不为空,进队。循环就可以了。。。。
typedef struct d{
int data
struct d *left
struct d *right
}tree
tree *buildtree(int *a,int &n)
{
int num=a[n++]
if(num==NULL)
{
return NULL
}
tree *s=(tree *)malloc(sizeof(tree))
s->data=num
s->left=buildtree(a,n)
s->right=buildtree(a,n)
return s
}
void layer(tree *t)
{
if(t!=NULL)
{
tree *queue[max]
tree *tmp
int rear,front
front=rear=0
queue[rear++]=t
while(front!=rear)
{
tmp=queue[front++]
printf("%d->",tmp->data)
if(tmp->left!=NULL)
{
queue[rear++]=tmp->left
}
if(tmp->right!=NULL)
{
queue[rear++]=tmp->right
}
}
}else
{
printf("the tree is empty!")
return
}
}
int main()
{
int a[]={1,2,4,0,0,5,0,0,3,6,0,0,7,0,0}
int n=0
tree *t=buildtree(a,n)
layer(t)
}