Binary Tree Design Algorithm

• 10-29-2012, 07:25 AM
Googol
Binary Tree Design Algorithm
I am currently learning how to use binary trees, but I am having trouble getting started on how to design basic methods. The simplest of the methods I need to write is finding the maximum number in an unsorted binary tree. I think if I could just see a method I could get an idea on how to travel throughout a binary tree.
I know that sending a value such as 0 for my initial max is a bad idea just in case all of the input is negative, but I am not sure how to grab some leaf from the tree as my starting max value.

The input is something like this. (((10 16) -2 25) (33 4) 21 59)

Code:

```public static int findMax (Object tree) {   return findMax2(tree, 0); } public static int findMax2 (Object tree, int max) {         if (method returning boolean for tree)         {                 int left = findMax2(lhs((Cons)tree), max);                 int right = findMax2(rhs((Cons)tree), max);                 max = left > right ? left : right;         }         else if (method returning boolean for leaf)         {                 int curr = (int) (Integer) tree;                 max = curr > max ? curr : max;         }         return max; }```
• 10-29-2012, 02:33 PM
KevinWorkman
Re: Binary Tree Design Algorithm
You could set your initial value to negative infinity, or just the first value you come across.