编写一个按层次遍历二叉树的算法。树的结构以广义表的形式给出。如A(B,)
表示一颗有 22 个节点的树。其中根的data
值为A
,其左孩子为叶子节点,data
值为B
,右孩子为空。
输入格式
输入有一行,为广义表形式给出的树形结构。
输出结构
输出也是一行,为该二叉树按层次遍历的结果序列,每个元素之间用空格隔开,行末不需要多余的空格。
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <string.h>
#define ERROR 0
#define OK 1
typedef struct Node{
char data;
struct Node *lchild, *rchild;
}Node;
Node *init_node(char val){
Node *p = (Node *)malloc(sizeof(Node));
p->data = val;
p->lchild = p->rchild = NULL;
return p;
}
void clear_node(Node *node){
if (node == NULL) return;
clear_node(node->lchild);
clear_node(node->rchild);
free(node);
}
//广义表输入转二叉树
//遇左括号将元素p入栈,左括号后元素q为栈顶元素左孩子,逗号后元素为栈顶右孩子
//右括号出栈
typedef struct Stack{
Node **data;//????
int top, size;
} Stack;
Stack *init_stack(int n){
Stack *s = (Stack *)malloc(sizeof(Stack));
s->data = (Node **)malloc(sizeof(Node *)* n);//记录节点地址
s->size = n;
s->top = -1;
return s;
}
void clear_stack(Stack *s){
if (s == NULL) return ;
free(s->data);
free(s);
return;
}
Node *top(Stack *s){
return s->data[s->top];
}
int empty(Stack *s){
return s->top == -1;
}
int push(Stack *s, Node *val){
if (s == NULL) return 0;
if (s->top == s->size - 1) return 0;//栈满
//expand
s->data[++(s->top)] = val;
return 1;
}
int pop(Stack *s){
if (s == NULL) return 0;
if (empty(s)) return 0;
s->top--;
return 1;
}
//广义表建树
Node *table_build(const char *str){
Stack *s = init_stack(strlen(str));
Node *temp = NULL, *p = NULL;//p为根节点
int flag = 0;
while(str[0]){
switch (str[0]){
case '(':
push(s, temp);
flag = 0;
break;
case ',':
flag = 1;
break;
case ')':
p = top(s);//??
pop(s);
break;
default:
//遇字母,设为栈顶的孩子
temp = init_node(str[0]);
if(!empty(s) && flag == 0){
top(s)->lchild = temp;
}
else if(!empty(s) && flag == 1){
top(s)->rchild = temp;
}
break;
}
str++;
}
clear_stack(s);
if (temp && !p) p = temp;//只有一个根,此时p为空
return p;
}
typedef struct Queue{
Node *data;
int head,tail,length;
}Queue;
void Queue_init(Queue *q, int length) {
q->data=(Node *)malloc(sizeof(Node)*length);
q->head=0;
q->tail=-1;
q->length=length;
}
int Queue_push(Queue *q, Node *element) {
if(q->tail + 1 >= q->length) {
return ERROR;
}
q->tail++;
q->data[q->tail] = *element;
return OK;
}
Node *Queue_front(Queue *q) {
return q->data+q->head;
}
void Queue_pop(Queue *q) {
q->head++;
}
int Queue_empty(Queue *q) {
return q->head>q->tail;
}
void Queue_clear(Queue *q) {
free(q->data);
free(q);
}
int main(){
char str[100];
gets(str);
int temp1=(int)strlen(str);
Queue *queue=(Queue *)malloc(sizeof(Queue));
Queue_init(queue,temp1);
Node *root=table_build(str);
if(temp1!=0)
{
Queue_push(queue,root);
while(!Queue_empty(queue))
{
Node *temp=Queue_front(queue);
printf("%c ",temp->data);
Queue_pop(queue);
if(temp->lchild)
{
Queue_push(queue,temp->lchild);
}
if(temp->rchild)
{
Queue_push(queue,temp->rchild);
}
}
}
else
{
printf("");
}
return 0;
}