# How to find the larget number on binary search tree

• December 23rd, 2011, 08:58 AM
Jurgen
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?
• December 23rd, 2011, 10:06 AM
Freaky Chris
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
• December 24th, 2011, 05:04 AM
Jurgen
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; }```
• December 24th, 2011, 07:21 AM
mar
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!
• December 24th, 2011, 11:26 AM
copeg
Re: How to find the larget number on binary search tree