recursion - Create and traverse a binary tree recursively in C -
i want create binary tree , traverse preorder traversal, , use recursive method. these code can compiled can not run correctly, , found maybe can not finish createbitree()
function, don't know problem is.
#include <stdio.h> #include <malloc.h> typedef struct binode{ int data; struct binode *lchild; struct binode *rchild; //left , 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 binary tree 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 binary tree preorder traversal if(t != null) { printf("%c\n", t -> data); traversebitree(t -> lchild); traversebitree(t -> rchild); } return 1; }
for example, when input preorder sequence "abc##de#g##f###"("#"means space), , still let me input, think traversebitree()
function hasn't been executed.
an assignment of pointer value pointer within function not have effect outside scope of function. doing this:
int createbitree(binode *t) { /* ... */ t = null;
is same doing this:
int func(int i) { /* ... */ = 0;
a pointer argument necessary in these cases:
int createbitree(binode **t) { /* ... */ t[0] = null; // or... *t = null;
with changes initial code:
int main() { binode *t; createbitree(&t); traversebitree(t); return 0; } int createbitree(binode **t) { //create binary tree 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; }
Comments
Post a Comment