2 Replies - 3381 Views - Last Post: 04 October 2011 - 06:31 AM Rate Topic: -----

#1 assert(C)  Icon User is offline

  • D.I.C Head

Reputation: 1
  • View blog
  • Posts: 71
  • Joined: 20-July 11

find min and max value of BST in C

Posted 04 October 2011 - 05:06 AM

Hey Guys,

I have made these two functions two find the min and max value of a BST. They dont seem to work I want the functions to be recursive; When I run my code it will not give the minium value.

 int minVal(tree Ptr){
   int minValue=0;
   if (Ptr != NULL){
       minVal(Ptr->left);
       minValue=Ptr->data;
   }
   return minValue;
}





Thanks
Is This A Good Question/Topic? 0
  • +

Replies To: find min and max value of BST in C

#2 sepp2k  Icon User is offline

  • D.I.C Lover
  • member icon

Reputation: 2013
  • View blog
  • Posts: 3,037
  • Joined: 21-June 11

Re: find min and max value of BST in C

Posted 04 October 2011 - 05:47 AM

You're calling minVal recursively, but you're not doing anything with the result of the recursive call. You should return the result of recursive call if Ptr->left is not null, otherwise you should return the data of the current node.
Was This Post Helpful? 0
  • +
  • -

#3 baavgai  Icon User is offline

  • Dreaming Coder
  • member icon

Reputation: 5642
  • View blog
  • Posts: 12,359
  • Joined: 16-October 07

Re: find min and max value of BST in C

Posted 04 October 2011 - 06:31 AM

int minVal(tree Ptr){
	// there variable here is kind of pointless
	// you could just return it
	// int minValue=0;
	if (Ptr != NULL){
		// visit the left child
		minVal(Ptr->left);
		// now, completely ignore 
		// what might have been returned from the
		// call and return the current value
		return minValue;
	}
}



So, it looks like you'll return the value of the first node you visit.

While checking for NULL down one level is classic in recursion, I'd recommend you start like:
int minVal(tree Ptr){
	if (Ptr->left == NULL) {
		// you're there, now what do you do?


Was This Post Helpful? 0
  • +
  • -

Page 1 of 1