Shubh Shubh - 3 months ago 17
C Question

Searching in a tree (tree is not BST)

#include<stdio.h>
#include<stdlib.h>


It just prints whatever data I pass, if possible please suggest for some optimization.

struct node{
int data;
struct node* left;
struct node* right;
};


For new Node Creation



struct node* newNode(int data)
{
struct node* node= malloc(sizeof(struct node));
node->data=data;
node->left=NULL;
node->right=NULL;
return node;
}


Returns height of tree



int height(struct node* root) //returns height of a tree
{
int lheight,rheight;
if(root==NULL)return;
else
{
lheight=height(root->left);
rheight=height(root->right);
}
if(lheight>rheight)
return lheight+1;
else return rheight+1;
}


Search Function



void levelordersearch(struct node* root,int curr,int level,int num)
{
if(root==NULL) return;
if(curr==level)
{
if(root->data=num)
printf("Found %d at level %d\n",root->data,level);
exit(-1);
else printf("Not Found\n");
}
else
{
levelordersearch(root->left,curr+1,level,num);
levelordersearch(root->right,curr+1,level,num);
}

}


For each level traversal



void level(struct node* root,int data)
{
int h,i;
h=height(root);
for(i=1;i<=h;i++)
{
levelordersearch(root,1,i,data);
}
}


Driver program to test the Functionality



int main()
{
struct node *root = newNode(1);

root->left = newNode(2);
root->right = newNode(3);
root->left->left = newNode(4);
root->left->right = newNode(5);
level(root,90);
return 0;
}

Answer

Problem is in your search funtion, a simple typo

if(curr==level) { if(root->data==num)
printf("Found %d at level %d\n",root->data,level); exit(-1); else printf("Not Found\n"); }
Instead of comparing values you have used an assignment operator which will always print a value.

Comments