I want to convert a binary tree to an array using C. I tried but was unsuccessful.
My binary tree contains the following elements (preorder)
4 3 5 10 8 7
but my array contains (after sorting)
4 4 5 7 8 10
Any help would be greatly appreciated. My current code look like this:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
typedef struct tree
{
int data;
struct tree *left;
struct tree *right;
}tree;
int AddToArray(tree *node, int arr[], int i);
tree *CreateNode(int data);
tree *Insert(tree *node, int data);
void PrintPreorder(tree *node);
int count(tree *node);
int compare(const void * a, const void * b);
//---------------------------------------------------------------------------
int main()
{
int i;
int size;
int *arr=NULL;
tree *root=NULL;
printf("***TEST PROGRAM***\n");
root = Insert(root, 4);
root = Insert(root, 3);
root = Insert(root, 5);
root = Insert(root, 10);
root = Insert (root, 8);
root = Insert (root, 7);
size = count(root);
printf("\n***BINARY TREE (PREORDER)***\n");
PrintPreorder(root);
printf("\nThe binary tree countain %d nodes", size);
printf("\n\n***ARRAY***\n");
arr = calloc(size, sizeof(int));
AddToArray(root, arr, 0);
qsort(arr,size,sizeof(int),compare);
for (i=0; i<size; i++)
{
printf("arr[%d]: %d\n", i, arr[i]);
}
}
//---------------------------------------------------------------------------
int compare(const void * a, const void * b)
{
return ( *(int*)a - *(int*)b );
}
int AddToArray(tree *node, int arr[], int i)
{
if(node == NULL)
return i;
arr[i] = node->data;
i++;
if(node->left != NULL)
AddToArray(node->left, arr, i);
if(node->right != NULL)
AddToArray(node->right, arr, i);
arr[i] = node->data;
i++;
}
tree *CreateNode(int data)
{
tree *node = (tree *)malloc(sizeof(tree));
node -> data = data;
node -> left = node -> right = NULL;
return node;
}
tree *Insert(tree *node, int data)
{
if(node==NULL)
{
tree *temp;
temp = CreateNode(data);
return temp;
}
if(data >(node->data))
{
node->right = Insert(node->right,data);
}
else if(data < (node->data))
{
node->left = Insert(node->left,data);
}
/* Else there is nothing to do as the data is already in the tree. */
return node;
}
void PrintPreorder(tree *node)
{
if(node==NULL)
{
return;
}
printf("%d ",node->data);
PrintPreorder(node->left);
PrintPreorder(node->right);
}
int count(tree *node)
{
int c = 1;
if (node == NULL)
return 0;
else
{
c += count(node->left);
c += count(node->right);
return c;
}
}
Change your AddToArray method to this:
int AddToArray(tree *node, int arr[], int i)
{
if(node == NULL)
return i;
arr[i] = node->data;
i++;
if(node->left != NULL)
i = AddToArray(node->left, arr, i);
if(node->right != NULL)
i = AddToArray(node->right, arr, i);
return i;
}
What was happening was that your recursive calls were changing the value of i (the index where you were supposed to insert the following element), but your recursion wasn't changing the value of i in the iteration that actually invoked the recursion. Updating i with the value returned by AddToArray fixes this.
Cause that i is not treated in a unified manner.
AddToArray replace with
void AddToArray(tree *node, int arr[], int *i){
if(node == NULL)
return ;
arr[*i] = node->data;
++*i;
AddToArray(node->left, arr, i);
AddToArray(node->right, arr, i);
}
and call i=0; AddToArray(root, arr, &i); at main.
The two lines of code int AddToArray
arr[i] = node->data;
i++;
Are appearing twice at each level of recursion. My guess is that every value in the tree is being written to the array twice and they over lap each other. but the root is the final value to be written twice so it is the only noticeable one.
Just remove the duplicate call at the bottom of the function.
int TreeToArray (struct node *tree, int *arr, int i)
{
if (tree == NULL) return i;
if (tree->left != NULL) i = TreeToArray(tree->left, arr, i);
arr[i] = tree->Value;
i++;
if (tree->right != NULL) i = TreeToArray(tree->right, arr, i);
return i;
}
Related
I am making a program to test out binary search trees in the c language. I want to balance it using a less good array method. I dynamically allocate the array based on the number of nodes in the BST and send the array off to another function that does the search and should place the elements in the array. However, when I run the program just the first element (the root of the tree) shows up in the array with every other iteration nothing happens. I am not sure on what is wrong.
Below is a MCVE for the part of the program that does not work. The first code blocks are simply to make and fill a BST. And it's the sorterToArray function that does not work.
In the recursive function sorterToArray I have tried to send the next place in the array but that does not work since it "is a nullptr".
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
struct treeNode
{
int data;
struct treeNode* left;
struct treeNode* right;
};
typedef struct treeNode* BSTree;
void insertSorted(BSTree* tree, int data);
void sorterToArray(struct treeNode* temp, int* pArray, int i);
int counter(int i, const BSTree tree);
void goLeftAndRight(struct treeNode* newNode, struct treeNode* tempTree, const int data);
void balanceTree(BSTree* tree);
static int* writeSortedToArray(const BSTree tree);
int main(void) {
BSTree tree = NULL;
insertSorted(&tree, 10);
for (int i = 0; i < 9; i++)
insertSorted(&tree, i + 20);
balanceTree(&tree);
}
static struct treeNode* createNode(int data)
{
//Creates the new node for the tree
struct treeNode* newNode;
//Allocates memory for the new node
newNode = calloc(1, 1 + sizeof(struct treeNode*));
//Tests the new memory
assert(newNode != NULL);
//Assigns data to the new node
newNode->data = data;
//Sets the left and right pointers to NULL so that other functions know where the ends are
newNode->left = NULL;
newNode->right = NULL;
return newNode; //Returns the new node
}
void insertSorted(BSTree* tree, int data)
{
//Creates a new temp struct
struct treeNode* newNode = createNode(data);
struct treeNode* tempTree = (*tree);
//If the tree is empty then the data will be at the root
if (tempTree == NULL) {
(*tree) = newNode;
}
//If the tree is not empty the function will call the help function in order to find the right node.
else {
goLeftAndRight(newNode, tempTree, data);
}
}
void goLeftAndRight(struct treeNode* newNode, struct treeNode* tempTree, const int data) {
if (data < tempTree->data && tempTree->left == NULL) {
tempTree->left = newNode;
return;
}
else if (data > tempTree->data && tempTree->right == NULL) {
tempTree->right = newNode;
return;
}
if (data < tempTree->data && data != tempTree->data) {
goLeftAndRight(newNode, tempTree->left, data);
}
else if (data > tempTree->data && data != tempTree->data) {
goLeftAndRight(newNode, tempTree->right, data);
}
}
int counter(int i, const BSTree tree) {
if (tree->left != NULL)
i = 1 + counter(i, tree->left);
if (tree->right != NULL)
i = 1 + counter(i, tree->right);
return i;
}
void balanceTree(BSTree* tree) {
int* sortedArray = writeSortedToArray((*tree));
}
//Code blocks writeSortedToArray ans SorterToArray are the ones causing the problems.
static int* writeSortedToArray(const BSTree tree)
{
struct treeNode* temp = tree;
int i = 0, number = 1 + counter(i, tree);
int* pArray = calloc(number, sizeof(int*));
assert(pArray != NULL);
sorterToArray(temp, pArray, i);
return pArray;
}
//Function where the problem is most likely located.
void sorterToArray(struct treeNode* temp, int* pArray, int i) {
if (temp->left != NULL)
sorterToArray(temp->left, pArray, i);
pArray[i] = temp->data;
i = i + 1;
if (temp->right != NULL)
sorterToArray(temp->right, pArray, i);
}
The problem is indeed in the function you point to. The variable i is local to the function's execution context, and each recursive execution has thus its "own" i. The i = i + 1 only affects one local instance, while other versions of i don't change. That means that none of those i variables will ever get the value 2 or more.
Otherwise put: i is passed by value to the recursive function call.
The solution is to have the function return the updated value of i to the caller:
int sorterToArray(struct treeNode* temp, int* pArray, int i) {
if (temp->left != NULL)
i = sorterToArray(temp->left, pArray, i);
pArray[i] = temp->data;
i = i + 1;
if (temp->right != NULL)
i = sorterToArray(temp->right, pArray, i);
return i;
}
The program is supposed to take a user entered integer and convert it into binary through a stack of singly linked lists. I think it's either my toBin() function or my printStack() function that's causing the infinite loop.
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
typedef struct node_def node;
struct node_def
{
int val;
node *next;
};
node *head;
void push(int val);
void pop(node *head);
int top();
void printStack();
int toBin(int val);
int main()
{
int num = 0;
printf("Enter an integer: ");
scanf("%d", &num);
push(num);
toBin(num);
printStack();
return 0;
}
void push(int val)
{
node *new;
new = malloc(sizeof(node));
if (head == NULL)
{
head = malloc(sizeof(node));
head->next = NULL;
head->val = val;
}
else
{
new->next = head;
new->val = val;
head = new;
}
return;
}
void pop(node *head)
{
node *tmp;
if(head == NULL)
{
printf("Stack is Empty\n");
return;
}
else
{
tmp = head;
head = head->next;
free(tmp);
}
return;
}
int top()
{
return(head->val);
}
void printStack()
{
node *tmp;
tmp = head;
if(head == NULL)
{
return;
}
while(head != NULL)
{
printf("%d ", head->val);
head = head->next;
}
printf("\n");
return;
}
int toBin(int val)
{
pop(head);
int i = 1, remainder, binary;
while(val != 0)
{
remainder = val % 2;
binary = binary + remainder * i;
val = val / 2;
i = i * 10;
push(binary);
}
return val;
}
You run into an infinite loop due to not properly initialising your variables. In particular, you have no guarantees that your node* head will be initialised to NULL, or that your int variables in toBin() will be initialised to zero.
Always, always, always initialise your variables when programming in C/C++.
Fixing these bugs and removing unused code leaves us with:
#include <stdio.h>
#include <stdlib.h>
typedef struct node_def node;
struct node_def
{
int val;
node *next;
};
/* Note that we are initialising the global variable to NULL. */
node *head = NULL;
void push(int val);
void printStack();
int toBin(int val);
int main()
{
int num = 0;
printf("Enter an integer: ");
scanf("%d", &num);
/* Removed push(num), as you're using parameters in the following call: */
toBin(num);
printStack();
return 0;
}
/* Changed printStack to use a tmp pointer to
traverse the stack without mutating it */
void printStack()
{
node* tmp = head;
while(tmp != NULL)
{
printf("%d ", tmp->val);
tmp = tmp->next;
}
printf("\n");
return;
}
int toBin(int val)
{
/* Removed pop() as you're getting val from parameters */
/* Also initialising remainder and binary variables */
int i = 1, remainder = 0, binary = 0;
while(val != 0)
{
remainder = val % 2;
binary = binary + remainder * i;
val = val / 2;
i = i * 10;
push(binary);
}
return val;
}
/* It's a stack so no if's are necessary for pushing */
void push(int val)
{
node *new = malloc(sizeof(node));
new->val = val;
new->next = head;
head = new;
return;
}
Guys below code works fine until size= 100000. However it gives me stack overflow error after size=200000.
How can i fix that ?
Is there some way to optimize it ?
#include <stdio.h>
#include <stdlib.h>
#include <malloc.h>
#define SIZE 500000
// HELPER ARRAY FUNCTIONS
void check(int *arr)
{
int i = 0;
for (i = 0; i < SIZE - 1; i++)
{
if (arr[i]>arr[i + 1])
{
printf("Not sorted.\n");
return;
}
}
printf("Sorted.\n");
}
void fill_array(int *arr)
{
int i = 0;
for (i = 0; i < SIZE; i++)
arr[i] =rand()%100;
}
void print_array(int *arr)
{
int i;
for (i = 0; i < SIZE; i++)
printf("%d ", arr[i]);
printf("\n");
}
// NODE STRUCT
typedef struct BST_NODE
{
struct BST_NODE *left, *right;
int data;
}node;
// TREE FUNCTIONS
node* generate_node(int *value)
{
node *n = (node*)malloc(sizeof(node));
n->left = NULL;
n->right = NULL;
n->data = *value;
return n;
}
node* insert_node(node *n, int *value)
{
if (n == NULL)
return generate_node(value);
if (*value < n->data)
n->left = insert_node(n->left, value);
else
n->right = insert_node(n->right, value);
return n;
}
node* construct_BST(int *arr, node* n)
{
int i;
n = NULL;
for (i = 0; i < SIZE; i++)
n = insert_node(n, &arr[i]);
return n;
}
int s = 0;
void LVR(int *arr, node* n)
{
if (n != NULL)
{
LVR(arr, n->left);
arr[s] = n->data;
s++;
LVR(arr, n->right);
}
}
void tree_sort(int *arr)
{
node *root = (node*)malloc(sizeof(node));
root = construct_BST(arr, root);
LVR(arr, root);
}
// DRIVER PROGRAM
int main()
{
int *Array = (int*)malloc(sizeof(int)*SIZE);
fill_array(Array);
tree_sort(Array);
print_array(Array);
check(Array);
free(Array);
getchar();
return 0;
}
It gives an error at this part below:
node* generate_node(int *value)
{
node *n = (node*)malloc(sizeof(node));
n->left = NULL;
n->right = NULL;
n->data = *value;
return n;
}
As already pointed out by other people, the problem is that the depth of the tree will be SIZE in the worst case.
In the case of your code, since the value to hold is a value less than 100, you can suppress the depth of the tree by not creating a new node for the same value.
In case of the same value change to count up as follows.
#include <stdio.h>
#include <stdlib.h> //stdlib.h include malloc and free
#define SIZE 500000
typedef struct BST_NODE {
struct BST_NODE *left, *right;
int data;
int count;//Add for count
} node;
node* generate_node(int value){//just use int
node *n = (node*)malloc(sizeof(node));//C does not need to cast from void *.
n->right = n->left = NULL;
n->data = value;
n->count = 1;//set 1 at first time
return n;
}
node* insert_node(node *n, int value){
if(n == NULL)
return generate_node(value);
if(value < n->data)
n->left = insert_node(n->left, value);
else if (value > n->data)
n->right = insert_node(n->right, value);
else
n->count++;//Add count up
return n;
}
node* construct_BST(int *arr){//no need node *n as argument
int i;
node *n = NULL;
for (i = 0; i < SIZE; i++)
n = insert_node(n, arr[i]);
return n;
}
int s = 0;
void LVR(int *arr, node *n){
if (n != NULL){
int i;
LVR(arr, n->left);
for(i = 0; i < n->count; ++i)
arr[s++] = n->data;//Repeat as many times as count
LVR(arr, n->right);
}
}
void tree_free(node *n){
if(n){
tree_free(n->left);
tree_free(n->right);
free(n);
}
}
void tree_sort(int *arr){
node *root = construct_BST(arr);
s = 0;//Necessary for different calls
LVR(arr, root);
tree_free(root);//release tree
}
If you're getting a stack overflow, that means your function call stack is getting too deep. That can happen when building a binary search tree if the tree ends up being unbalanced.
Best case, your tree height will be O(log n), worst case it will be O(n). If you place items into the tree in sorted order, your binary tree will degenerate into a linked list and you'll hit the worst case.
For this particular example, you're generating random numbers from 0 to 99. You might get more randomize results if you increase the range of the numbers. So instead of using rand()%100, use something like rand()%10000. That might help keep the height of the tree down.
On an unrelated note, you have a memory leak. First, the initial node you allocate for the root of the tree gets overwritten, so you don't need it. Second, you never bother to free the tree structure.
You can take care of these as follows:
void free_tree(node *root)
{
if (root) {
free_tree(root->left);
free_tree(root->right);
free(root);
}
}
void tree_sort(int *arr)
{
node *root = NULL
root = construct_BST(arr, root);
LVR(arr, root);
free_tree(root);
}
I am trying to see if tree A is the preorder traversal of tree B and to do so, I created two trees which during a transversal were supposed to save the values. However, after hours of debugging I found out that the trees values were ALWAYS 0. I am confused as to why the trees values are 0. I've done a multitude of print statements (some of which I've left in the code posted below) and I just cannot seem to pinpoint why this is happening. Can someone please nudge me in the correct direction? I thought maybe the function was deleting variables as it exited and in effort to get to the bottom of the issue I had the preorder function return the tree ( as seen below), however, the output is ALWAYS 0 for the tree.
Code:
typedef struct node
{
// Each node holds a single integer.
int data;
// Pointers to the node's left and right children.
struct node *left, *right;
} node;
int tree_diff(node *a, node *b)
{
if (a == NULL && b == NULL)
return 0;
else if (a == NULL || b == NULL)
return 1;
else if (a->data != b->data)
return 1;
printf("A %d , B %d", a->data, b->data);
return tree_diff(a->left, b->left) || tree_diff(a->right, b->right);
}
node *preorder_recursive(node *root, node *A)
{
if (root == NULL)
return A;
printf("root %d ", root->data);
A = root;
printf("= data %d\n", A->data);
preorder_recursive(root->left, A->left);
preorder_recursive(root->right, A->right);
}
void postorder_recursive(node *root, node *B)
{
if (root == NULL)
return;
B = root;
postorder_recursive(root->left, B->left);
postorder_recursive(root->right, B->right);
printf("root %d ", root->data);
printf("= data %d\n", B->data);
}
int kindredSpirits(node *a, node *b)
{
// Get the preorder of a
node *A = malloc(sizeof(node));
A = preorder_recursive(a, A);
// Get the postorder of b
printf("\n\n");
node *B = malloc(sizeof(node));
postorder_recursive(b, B);
if(tree_diff(A,B) == 1)
return 0;
else
return 1;
}
The test case:
#include <stdio.h>
#include <stdlib.h>
#include "KindredSpirits.h"
node *create_node(int data)
{
node *n = malloc(sizeof(node));
n->data = data;
n->left = n->right = NULL;
return n;
}
node *forest_fire(node *root)
{
if (root == NULL)
return NULL;
forest_fire(root->left);
forest_fire(root->right);
free(root);
}
int main(void)
{
node *root;
root = create_node(23);
root->left = create_node(12);
root->left->left = create_node(5);
root->left->right = create_node(18);
root->right = create_node(71);
root->right->right = create_node(56);
printf("%s\n", !kindredSpirits(root, root) ? "Success!" : "fail whale :(");
forest_fire(root);
return 0;
}
Here's a code fragment that should get you started:
typedef struct node {
// Each node holds a single integer.
int data;
// Pointers to the node's left and right children.
struct node *left,
struct node *right;
} node;
typedef struct list {
int lst_max; // maximum number of allocated cells
int lst_cur; // current number of filled cells
int *lst_base; // traversal list
} list;
list list_a = { 0, 0, NULL };
list list_b = { 0, 0, NULL };
void
list_append(list *lst,int data)
{
int newidx;
newidx = lst->lst_cur;
if (newidx >= lst->lst_max) {
lst->lst_max += 100;
lst->lst_base = realloc(lst->lst_base,sizeof(int) * lst->lst_max);
if (lst->lst_base == NULL) {
printf("list_append: malloc error\n");
exit(1);
}
}
lst->lst_base[newidx] = data;
lst->lst_cur = newidx + 1;
}
void
preorder_recursive(node *root,list *lst)
{
if (root == NULL)
return;
list_append(lst,root->data);
preorder_recursive(root->left,lst);
preorder_recursive(root->right,lst);
}
void
postorder_recursive(node *root,list *lst)
{
if (root == NULL)
return;
postorder_recursive(root->left,lst);
postorder_recursive(root->right,lst);
list_append(lst,root->data);
}
int
main(void)
{
preorder_recursive(a,&list_a);
postorder_recursive(b,&list_b);
// compare list_a and list_b ...
return 0;
}
I'm trying to write a function that figures out if tree a's preorder is equal to tree b's postorder without altering a or b.
I use arrays to save the traversals and then compare the value of the two arrays.
#define MAX_TREE_SIZE 100
void preorder_recursive(node *root, int* arr, int *len) {
if (root != NULL){
arr[(*len)++] = root->data;
preorder_recursive(root->left, arr, len);
preorder_recursive(root->right, arr, len);
}
}
void postorder_recursive(node *root, int *arr, int *len) {
if (root != NULL){
postorder_recursive(root->left, arr, len);
postorder_recursive(root->right, arr, len);
arr[(*len)++] = root->data;
}
}
int kindredSpirits(node *a, node *b){
// Get the preorder of a
int *arr1 = malloc(MAX_TREE_SIZE * sizeof(int));
int len1 = 0;
preorder_recursive(a, arr1, &len1);
// Get the postorder of b
int *arr2 = malloc(MAX_TREE_SIZE * sizeof(int));
int len2 = 0;
postorder_recursive(b, arr2, &len2);
int ret = 0; // 2 traversals are equal
if (len1 != len2) {
ret = 1;
} else {
for (int i = 0; i < len1; i++){
if (arr1[i] != arr2[i]){
ret = 1;
break;
}
}
}
free(arr1);
free(arr2);
return ret;
}
This is my code,here I need to search a binary tree with the value x of type integer and need to return a pointer window of type BTREE of matching node.
Here programmes run into the case2,but still not searching for the node.I couldn't find my mistake.
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
typedef struct tree
{
int data;
struct tree *left;
struct tree *right;
}tree;
int AddToArray(tree *node, int arr[], int i);
tree *CreateNode(int data);
tree *Insert(tree *node, int data);
void PrintPreorder(tree *node);
int count(tree *node);
int compare(const void * a, const void * b);
//-------------------------------------------------------------------------------------------------
int main()
{
int i;
int choice;
int num;
int count;
int size;
int *arr=NULL;
tree *root=NULL;
while (1)
{
printf("enter your choice \n 1.Insert into tree \n");
printf("enter your choice \n 2.search element \n");
scanf("%d",&choice);
switch (choice)
{
case 1:
printf("Enter the input : \n");
scanf("%d",&num);
root = Insert(root, 4);
root = Insert(root, 3);
root = Insert(root, 5);
root = Insert(root, 10);
root = Insert (root, 8);
root = Insert (root, 7);
root = Insert(root,num);
break;
case 2:
printf("\n enter the element to be searched");
scanf("%d",&num);
for(i=0;i<100;i++)
{
if(arr[i]==num) {
printf("\n element found");
break;
}
}
if(i==count)
printf("\n element not found");
break;
}
printf("\n***BINARY TREE (PREORDER)***\n");
PrintPreorder(root);
}
}
/*intf("\n\n***ARRAY***\n");
arr = calloc(size, sizeof(int));
AddToArray(root, arr, 0);
qsort(arr,size,sizeof(int),compare);
for (i=0; i<size; i++)
{
printf("arr[%d]: %d\n", i, arr[i]);
}*/
//-------------------------------------------------------------------------------------------------
int compare(const void * a, const void * b)
{
return ( *(int*)a - *(int*)b );
}
int AddToArray(tree *node, int arr[], int i)
{
if(node == NULL)
return i;
arr[i] = node->data;
i++;
if(node->left != NULL)
AddToArray(node->left, arr, i);
if(node->right != NULL)
AddToArray(node->right, arr, i);
arr[i] = node->data;
i++;
}
tree *CreateNode(int data)
{
tree *node = (tree *)malloc(sizeof(tree));
node -> data = data;
node -> left = node -> right = NULL;
return node;
}
tree *Insert(tree *node, int data)
{
if(node==NULL)
{
tree *temp;
temp = CreateNode(data);
return temp;
}
if(data >(node->data))
{
node->right = Insert(node->right,data);
}
else if(data < (node->data))
{
node->left = Insert(node->left,data);
}
/* Else there is nothing to do as the data is already in the tree. */
return node;
}
void PrintPreorder(tree *node)
{
if(node==NULL)
{
return;
}
printf("%d ",node->data);
PrintPreorder(node->left);
PrintPreorder(node->right);
}
First of all allocate memory for arr
You are asking for binary tree but your code shows that you are using as if it is BST.[as for the add function].
Answer
If it is binary tree with no ordering then you have to search for all the nodes using standard tree traversal or BFS or DFS etc.
If it is `BST` then it will be easier.
1. Check the value x=root.val return root
2. else if( root.val> x) return search(x,root.left);
3. else return search(x,root.right);
One thing read about MCV example in SO. :)
Note 1: To allocate array you can have arr=malloc(sizeof(int)*n);
Note 2: If you are using array then you will store them this way
[ root root.left root.right root.left.left root.left.right root.right.left ... ]
1
/ \
2 3
/ \ / \
4 5 6 7
Note 3: Why are you using the array in this case..root can have access to any other node..if you don't want to dynamically allocate then only store them in a array otherwise you just dynamically insert necessary nodes when needed.
Code for searching in a BST (Binary Search Tree):
bool search(node * root, int x)
{
if(root->val==x)
return true;
else
{
if(x<root->val) //value is smaller go to the left subtree
return search(root->left,x);
else
return search(root->right,x);
}
}
Insertion algorithm BST
struct node* insert(struct node* node, int val)
{
if (node == NULL)
{
struct node *temp = malloc(sizeof(struct node));
temp->val = val;
temp->left = temp->right = NULL;
return temp;
}
if (val < node->val)
node->left = insert(node->left, val);
else if (val > node->val)
node->right = insert(node->right,val);
/* return the (unchanged) node pointer */
return node;
}
If you are using Binary tree
then you can also use some array [as we do in heap] or use a graph like structure (adjacency list..).
It is really upto your implementation.
Check this link for getting an idea - Binary tree implementation.
Searching in Binary tree
You can simply change the traversal code to this..
int levelOrder_Search(struct node* root)
{
struct Queue* queue = createQueue(SIZE);
Enqueue(root, queue);
while (!isEmpty(queue))
{
struct node* temp = Dequeue(queue);
if(temp->data==x)
return 1; // found :-)
if (temp->left)
Enqueue(temp->left, queue);
if (temp->right)
Enqueue(temp->right, queue);
}
return 0;//not found
}