Reputation: 111
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.
Upvotes: 2
Views: 4904
Reputation: 97948
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;
}
Upvotes: 4