search

Home  >  Q&A  >  body text

c++ - C语言算法指针问题?

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

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

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

高洛峰高洛峰2772 days ago415

reply all(2)I'll reply

  • 迷茫

    迷茫2017-04-17 15:18:14

    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.

    reply
    0
  • 怪我咯

    怪我咯2017-04-17 15:18:14

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

    reply
    0
  • Cancelreply