# binary trees-finding the maximum and min. value

• 09-21-2004
sachitha
binary trees-finding the maximum and min. value
are the following coding correct for finding the maximum value of a binary tree and to find the minimum value of a bin. tree??????

to find the maximum value:
int Tree::findMax(Node* localroot)
{
int max;
if(localroot!=NULL)
{
findMax(localroot->leftChild);
max=localroot->iData;
findMax(localroot->rightChild);
}
return max;
}//findMax
-----------------------------------------------
to find the minimum value:---

int Tree::findMin(Node* localroot)
{
int arr;
if(localroot!=NULL)
{
findMin(localroot->leftChild);
arr=localroot->iData;
return arr;
}
return -1;
}//findMin
• 09-21-2004
PJYelton
First off, use code tags when posting code.

Second off, no the code is not correct. You aren't comparing values, you just always return the local value. You need to compare the values returned from the left branch and the right branch with the current value, and return the min or max of the three.
• 09-21-2004
axon
well this is how I would do these methods:
Code:

```findMin( Node* t ) {         if( t == NULL )                 return NULL;         if( t->left == NULL )                 return t;         return findMin( t->left); } findMax( Node* t ) {         if( t != NULL )                 while( t->right != NULL )                         t = t->right;         return t; }```
• 09-21-2004
sachitha
hmm...i'm a little confused now with the last coding that was posted to this thread
??
i went through it now. It does work for the findMin(to find the minimum) right??
• 09-21-2004
sachitha
in my coding i'm not comparing the values b'coz im using part of the 'Inorder' traversing coding. So i thought because of that i'll naturally be getting the Minimum and the maximum values in the way that i've given my coding.
• 09-22-2004
axon
sachitha, the code I posted works on a binary search tree, which follows certain rules that makes the findMin() and findMax() a bit easier than in a common binary tree. If your tree is just a binary tree, you need some sort of a comparison system, if it is a search tree, my code will work.
• 09-23-2004
sachitha
oophs...i was referring to a 'Binary search tree' indeed. Thank you for the help! And sorry if i have confused anyone.