上面诗题目,下面是代码:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
typedef struct node {
struct node *lchild;
struct node *rchild;
int c;
} Node;
void postOrder(Node *T) {
if (T->lchild != NULL) {
postOrder(T->lchild);
}
if (T->rchild != NULL) {
postOrder(T->rchild);
}
printf("%d ", T->c);
}
void inOrder(Node *T) {
if (T->lchild != NULL) {
inOrder(T->lchild);
}
printf("%d ", T->c);
if (T->rchild != NULL) {
inOrder(T->rchild);
}
}
void preOrder(Node *T) {
printf("%d ", T->c);
if (T->lchild != NULL) {
preOrder(T->lchild);
}
if (T->rchild != NULL) {
preOrder(T->lchild);
}
}
Node *Insert(Node *T, int x) {
if (T == NULL) {
T = (Node *)malloc(sizeof(Node));
T->c = x;
T->lchild = T->rchild = NULL;
} else if(x < T->c) {
T->lchild = Insert(T->lchild, x);
} else if(x > T->c) {
T->rchild = Insert(T->rchild, x);
}
return T;
}
int main() {
int n;
while (scanf("%d", &n) != EOF) {
Node *T = NULL;
int i = 0;
int x = 0;
for (i = 0; i < n; i++) {
scanf("%d", &x);
T = Insert(T, x);
preOrder(T);
}
preOrder(T);
printf("\n");
inOrder(T);
printf("\n");
postOrder(T);
printf("\n");
}
return 0;
}
我编译的时候没有问题,可一运行就崩溃了。估计是指针出问题了,可我实在不知道该怎么改了,求大神指导。
在
void preOrder(Node *T)
函數實現的第6行,應該是preOrder(T->rchild);
而不是重複地preOrder(T->lchild);
,屬於粗疏錯誤,應該多學debug。1、
NODE *T
寫到while
外面2、
Insert
沒有處理等於的情況