How to find the larget number on binary search tree

This days I'm working on one assigment that has as purpose to create a Binary Search Tree that read a text files(which contains a String name and a double number) and implements some methods. Unfortunately i'm not very familiar with BST so I'm facing some difficulties. At the moment i want to write a method to search the BST to find and return the largest number. At the moment i'm using this code to do that but unfortunately i receive only the first number of the list and not the actual largest. Here is my method

Code java:

private double FindMaxElement(TreeNode maxElement)
{
double max = 0;
if(maxElement != null)
{
if(maxElement.number > max)
{
max = maxElement.number;
FindMaxElement(maxElement.left);
FindMaxElement(maxElement.right);
}
}
return max;
}

Can anyone help me or advice me with this method?

Re: How to find the larget number on binary search tree

There is alot wrong with this, for starters, max is always set to 0, so you are always comparing against 0, so chances are you number will be bigger than 0, unless its negative.

Secondly, where do you stor the result of the subsequent calls to FindMaxElement?

Chris

Re: How to find the larget number on binary search tree

Actually i made some changes, this time i point only on the right nodes but again i can't find the largest number instead the second most largest number appears! I'm not sure what the mistake is, what should i do with the max ?

Code :

private double FindMaxElement(TreeNode maxElement)
{
double max = 0;
if(maxElement.right != null)
{
if(maxElement.number > max)
{
max = maxElement.number;
FindMaxElement(maxElement.right);
if(FindMaxElement(maxElement.right) > max)
{
max = FindMaxElement(maxElement.right);
}
}
}
return max;
}

Re: How to find the larget number on binary search tree

Hi Jurgen,

Your method in general is very good, what i would like to say is that you need to have a public method (i think that you probably have created one and you don't show it here in this thread) in order to link it with this private method that you created. Also, in your private method you have only used if statements for the recursive case and not for the base case so you needed also to have an if statement for the base case in the case where the maxElement.right == null so that it could return 0.

Here is the code, i hope that it will work for you :

...

Let me know how it performed to you. Have a nice day!

Re: How to find the larget number on binary search tree

@mar, please read the forum rules and the following

http://www.javaprogrammingforums.com...n-feeding.html

@Jurgen, please do not double post the same question. Your question appears to be answered in your other thread - lets please keep discussions in that thread.

http://www.javaprogrammingforums.com...t-you-all.html