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.