Search function for a tree

84 Views Asked by At

I am working with a ternary search tree. Following code should give you an overview of how the tree looks like. Every leaf will contain a pointer to a linked list which contains pointer to the head node. Every leaf can have at most 3 nodes. Therefore after the root leaf has been filled with 3 data values the next value if it is smaller than the first node will get inserted in to the left if it is greater it gets inserted in to the right and if it is in the middle it will get inserted in to the centre child.

struct data
{
  int val;
};


struct node
{
  struct node* next;
  struct data* dta;
};

struct linkedList
{
  int size;
  struct node *head;
};

struct leaf
{
  struct linkedList* ll;
  struct leaf* left;
  struct leaf* right;
  struct leaf* center;
  struct leaf* parent;
};

struct tree
{
  struct leaf* root;
};

I am currently trying to create a function that takes in a tree and a int value as inputs. Then it checks every leaf in the tree to see if some leaf equals the int value and if it does it will return 1 and 0 otherwise.

Following is my code

int totalLeaf(struct leaf *lf)
{
  int sum = 0;
  struct node *temp = lf->ll->head;
  while(temp!=NULL)
  {
    sum = sum + temp->dta->val;
    temp = temp->next;
  }
  printf("sum is :  %d\n",sum);
  return sum;
}

int searchTotal(struct tree *tr,int total)
{
  if(tr->root == NULL)
  {
    return 0;
  }
  else
  {
    return searchTotal_r(tr->root,total);
  }
}

int searchTotal_r(struct leaf *lf,int total)
{
  if(lf==NULL)
  {
    return 0;
  }
  if(totalLeaf(lf) == total)
  {
    return 1;
  }
  else
  {
    searchTotal_r(lf->left,total);
    searchTotal_r(lf->center,total);
    searchTotal_r(lf->right,total);
  }

  return 0;
}

Can anyone suggest where i have gone wrong and how i can fix this issue?

1

There are 1 best solutions below

2
On BEST ANSWER
  else
  {
    searchTotal_r(lf->left,total);
    searchTotal_r(lf->center,total);
    searchTotal_r(lf->right,total);
  }

Change to:

  else
  {
    return searchTotal_r(lf->left,total) ||
           searchTotal_r(lf->center,total) ||
           searchTotal_r(lf->right,total);
  }

The way you currently have it, the recursive searches don't actually matter because you always return 0 even if you find something.