2

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.

2
  • When you say it doesn't work... What do you mean by that? Wrong out put? Segmentation fault? Something else? Commented May 19, 2013 at 4:18
  • 2
    You're passing your pointer values into CreateBiTree by value. The caller-side of that is never getting updated pointers (including itself). Commented May 19, 2013 at 4:19

1 Answer 1

4

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;
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.