c++ - C语言算法指针问题?
高洛峰
高洛峰 2017-04-17 15:16:14
0
2
409

上面诗题目,下面是代码:

#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;
}

我编译的时候没有问题,可一运行就崩溃了。估计是指针出问题了,可我实在不知道该怎么改了,求大神指导。

高洛峰
高洛峰

拥有18年软件开发和IT教学经验。曾任多家上市公司技术总监、架构师、项目经理、高级软件工程师等职务。 网络人气名人讲师,...

reply all(2)
迷茫

In the 6th line of the void preOrder(Node *T) function implementation, it should be preOrder(T->rchild); instead of repeated preOrder(T->lchild);. This is a rough mistake and you should learn more about debugging.

刘奇

1. NODE *T is written outside while
2. Insert does not handle the equal case

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template