# Thread: Fast generation of a binary tree

1. ## Fast generation of a binary tree

Hi all,

I am trying to generate a binary tree in C which considers all the possible combination for a number of array elements and a number of different options for each array element.

For example, consider that the array has 3 values which are the following:

Code:
```#define NO_OF_IDS 3
Array[NO_OF_IDS] = {ID1, ID2, ID3}```
And 2 different option (OPTION 1 and OPTION 2) for each array value.

Then the tree generated should be that: where 1 stands for OPTION 0 and 2 for OPTION 1.

I can create the above tree manually by using the code below:

Code:
```root = newNode(ROOT, 0);
/* HEIGHT 1 */
root->left = newNode(&Array, 0);
root->right = newNode(&Array, 1);
/* HEIGHT 2 */
root->left->left = newNode(&Array, 0);
root->left->right = newNode(&Array, 1);
root->right->left = newNode(&Array, 0);
root->right->right = newNode(&Array, 1);
/* HEIGHT 3 */
root->left->left->left = newNode(&Array, 0);
root->left->left->right = newNode(&Array, 1);
root->left->right->left = newNode(&Array, 0);
root->left->right->right = newNode(&Array, 1);

root->right->left->left = newNode(&Array, 0);
root->right->left->right = newNode(&Array, 1);
root->right->right->left = newNode(&Array, 0);
root->right->right->right = newNode(&Array, 1);```
where:

Code:
```struct node* newNode(char *String, uint8_t OPTION)
{
struct node* node = (struct node*)
malloc(sizeof(struct node));
node->String = String;
node->OPTION = OPTION;
node->left = NULL;
node->right = NULL;
return(node);
};

struct node
{
char* String;
struct node* left;
struct node* right;
uint8_t OPTION;
};```
The question is that: Can I create the tree in a faster way for a specific ID number?

Thank you all in advance.  2. Originally Posted by limp The question is that: Can I create the tree in a faster way for a specific ID number?
Yes, you can generate that tree using a function which takes, for instance, a root node as argument, an array and its size. Use some recursion for a simple solution. 3. Write a recursive function. Have you done any of those before?
Each call should create two child nodes, and call itself recursively for each of those two child nodes. It should also pass along the index of the item from 'Array' to add to that node. You stop when the index of the item from Array is beyond the end of the array. Popular pages Recent additions 