Friday, Jan 19th

Last update12:59:40 PM GMT

Write C code to search for a value in a binary search tree (BST).

Write e-mail
Simple ! just start with the root, and compare the search value to the root value. If value is equal is equal to the value of root, return the root. If value is less than the root node value, update the root to left of root else to right of the root.
There are two approach to this solution, one is using a while loop and other is recursive
The approach using while loop:

	mynode *search(int value, mynode *root)


	   while(root!=NULL && value!=root->value)


	     root = (value < root->value)?root->left:root->right;





Another way to do the same, in recursive way:

	mynode *recursive_search(int item, mynode *root)


	  if(root==NULL || item == root->value){return(root);}

	  if(item<root->info)return{recursive_search(item, root->left);}

	  return{recursive_search(item, root->right);}



Share this post

Web Hosting