-
Tree traversal
i'm trying to implement a pre order tree traversal on a name however i get an error "name undeclared in funtion pre order"
what have i done wrong? how do i fix it? will my code perform what i want it to? any help is appreciated;
Code:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
typedef struct tree
{
char name[20];
struct tree *left;
struct tree *right;
}Tree;
Tree *makenode( char *in, Tree *l, Tree *r)
{
Tree *t=malloc(sizeof(Tree));
t->left =l;
t->right =r;
strncpy(t->name,in,19);
return t;
}
Tree *insert( Tree *root, char *what)
{
if(root==NULL)
{root=makenode(what,NULL,NULL);}
else if(strcmp(what, root->name)<0)
{root->left =insert(root->left,what);}
else{root->right =insert(root->right,what);
}
return root;
}
char *preorder(Tree *root, char *what)
{
if(root==NULL)
{return "NOT FOUND";}
printf("%s ",root->name);
preorder(root->left,name);
preorder(root->right,name);
}
int main(void)
{
char s[20];
Tree *tree =NULL;
do{
scanf("%s",s);
if(strcmp(s,".")==0)
{break;}
if(strcmp(s,".")!=0);
{tree=insert(tree,s);}
}
while(strcmp(s,".")!=0);
preorder(tree,s);
return 0;
}
thanks
-
>what have i done wrong?
Just what the error says you've done wrong. You're using name, but name doesn't exist:
Code:
char *preorder(Tree *root, char *what)
{
if(root==NULL)
{return "NOT FOUND";}
printf("%s ",root->name);
preorder(root->left,name);
preorder(root->right,name);
}
It looks more like you want a binary search rather than a preorder traversal:
Code:
char *search(Tree *root, char *what)
{
if (root == NULL)
return "NOT FOUND";
else if (strcmp(what, root->name) < 0)
return search(root->left, what);
else if (strcmp(what, root->name) > 0)
return search(root->right, what);
else
return root->name;
}
-
ok looks like ive messed up badly , all i want to do is perform pre order tree traversal, e.g. go left, right , root , how do i do this?
-
>how do i do this?
Code:
void preorder(Tree *root)
{
if (root == NULL)
return;
printf("%s\n", root->name);
preorder(root->left);
preorder(root->right);
}
-