7:20~7:25 打卡学习
10:00~12:00 复习物理
15:00~17:00 看c加加
20:00~23:00 改进我之前的次序建树
好烦呀,原来我之前用数组模拟队列是错的,师父告诉我应该用链表模拟队列建树,唉,难怪我二叉树的题老是过不了。
原先用数组模拟队列建的树:
#include<stdio.h>
#include<stdlib.h>
#define LEN sizeof(struct TREE)
struct TREE
{
char data;
struct TREE*l,*r;
};
typedef struct TREE A;
A* fun1()
{
int x,n=0,head=0,tail=0,i=1;
A que[1010],*temp;
while(scanf("%d",&x))
{
if(x==-1) break;
que[tail++].data=x;
//printf("x=%d",x);
}
//printf("tail=%d\n",tail);
if(que[0].data==0) return NULL;
while(head!=tail)
{
if((que[head].l==NULL&&que[head].data!=0)||que[head].data==-1)
que[head].l=&que[i++];
if((que[head].r==NULL&&que[head].data!=0)||que[head].data==-1)
que[head].r=&que[i++];
head++;
}
//printf("head=%d\n",head);
temp=que;
return temp;
}
void fun2(A * p)
{
if((p!=NULL&&p->data!=0)&&p->data!=-1)
{
fun2(p->l);
fun2(p->r);
printf("%d ",p->data);
p->data=-1,p->l=NULL,p->r=NULL;
}
}
int fun3(A *p)
{
if((p==NULL||p->data==0)||p->data==-1) return 0;
int a=fun3(p->l),b=fun3(p->r),max;
max=(a>b)?a:b;
return max+1;
}
int main()
{
int T;
scanf("%d",&T);
while(T--)
{
A* p,*q;
p=fun1(),q=p;
printf("%d ",fun3(p));
fun2(q);
printf("\n");
}
}
改进后:
#include <stdio.h>
#include <stdlib.h>
struct node
{
int data;
struct node *l, *r;
};
typedef struct node node;
node *fun()
{
int head = 0, tail = 0, a[1010], index = 0, n = 0, x;
node *que[1010]; //队列
while (scanf("%d", &x) != EOF) //输入
{
if (x == -1)
break;
a[n++] = x;
}
// for (int i = 0; i < n; i++)
// printf("%d ", a[i]);
// putchar('\n');
node *root = (node *)malloc(sizeof(node)); //开辟根节点
root->l = root->r = NULL;
root->data = a[index++];
que[tail++] = root; //根节点入队
while (head != tail && index < n)
{
node *temp = que[head++]; //获取队首节点,并且pop
node *first = (node *)malloc(sizeof(node)); //开辟节点
first->l = first->r = NULL;
first->data = a[index++];
//printf("%d ", first->data);
if (first->data != 0) //
{
temp->l = first; //连接左节点
que[tail++] = first; //左节点入队
}
node *second = (node *)malloc(sizeof(node)); //开辟节点
second->l = second->r = NULL;
second->data = a[index++];
//printf("%d ", second->data);
if (second->data != 0) //
{
temp->r = second; //连接右节点
que[tail++] = second; //右节点入队
}
}
return root;
}
void postTrversal(node *temp) //后序遍历
{
if (temp == NULL)
return;
postTrversal(temp->l);
postTrversal(temp->r);
printf("%d ", temp->data);
}
int max(int a, int b)
{
return a > b ? a : b;
}
int height(node *temp)
{
if (temp == NULL)
return 0;
return max(height(temp->l), height(temp->r)) + 1;
}
int main()
{
int t;
scanf("%d", &t);
while (t--)
{
node *tree = fun();
printf("%d ",height(tree));
postTrversal(tree);
putchar('\n');
}
return 0;
}
好累呀,不想说更多了,早点睡啊吧,小秃头。