Create and traverse a binary tree recursively in C

三世轮回 提交于 2019-12-30 07:21:25

问题


I want to create a binary tree and traverse it by preorder traversal, and I use recursive method. These code can be compiled but can not run correctly, and I found it maybe can not finish the CreateBitree() function, but I don't know where the problem is.

#include <stdio.h>
#include <malloc.h>

typedef struct BiNode{
    int data;
    struct BiNode *lchild;
    struct BiNode *rchild;    //left and right child pointer
}BiNode;

int CreateBiTree(BiNode *T);
int TraverseBiTree(BiNode *T);

int main() {
    BiNode *t;
    CreateBiTree(t);
    TraverseBiTree(t);
    return 0;
}

int CreateBiTree(BiNode *T) {          //create a binary tree by preorder traversal
    char tmp;
    scanf("%c", &tmp);
    if(tmp == ' ')
    T = NULL;
    else {
        T = (BiNode *)malloc(sizeof(BiNode));
        T -> data = tmp;
        CreateBiTree(T -> lchild);
        CreateBiTree(T -> rchild);
    }
    return 1;
}

int TraverseBiTree(BiNode *T) {        //traverse a binary tree by preorder traversal
    if(T != NULL) {
        printf("%c\n", T -> data);
        TraverseBiTree(T -> lchild);
        TraverseBiTree(T -> rchild);
    }
    return 1;
}

For example, when I input a preorder sequence like "ABC##DE#G##F###"("#"means space), and then it still let me to input, I think the TraverseBiTree() function hasn't been executed.


回答1:


An assignment of a pointer value to a pointer within a function does not have any effect outside the scope of that function. Doing this:

int CreateBiTree(BiNode *T) { 
  /* ... */
  T = NULL;

is same as doing this:

int func(int i) { 
  /* ... */
  i = 0;

A pointer to the argument is necessary in these cases:

int CreateBiTree(BiNode **T) { 
  /* ... */
  T[0] = NULL;  // or... *T = NULL;

With some changes to the initial code:

int main() {
    BiNode *t; 
    CreateBiTree(&t);
    TraverseBiTree(t);
    return 0;
}

int CreateBiTree(BiNode **T) {          //create a binary tree by preorder traversal
    char tmp;
    scanf("%c", &tmp);
    if(tmp == ' ')
    T[0] = NULL;
    else {
        T[0] = (BiNode *)malloc(sizeof(BiNode));
        T[0]-> data = tmp;
        CreateBiTree(&(T[0]->lchild));
        CreateBiTree(&(T[0]->rchild));
    }   
    return 1;
}


来源:https://stackoverflow.com/questions/16631367/create-and-traverse-a-binary-tree-recursively-in-c

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!