I'm trying to find the car with the highest number of prizes. I visit each node of the tree and I get the array size and compare it with each node. However I can't seem to return the node with the highest value. Could anybody look at my code and point what's wrong with it?
Also I'm not sure if I'm returning it correctly from the recursive method mostPrizes
.
public class Car{
private String name;
private double key;
private ArrayList<Prize> Prizes;
public Car left;
public Car right;
public Car(String name)
{
this.name = name;
}
public double getKey() {
return key;
}
public void setKey(double key) {
this.key = key;
}
public ArrayList<Prize> getPrizes() {
return Prizes;
}
public void setPrizes(ArrayList<Prize> Prizes) {
this.Prizes = Prizes;
}}
public class main{
public Car root;
public void findWiner()
{
Car winner;
Car a = root;
Car b = root;
winner = mostPrizes(a,b)
public Car mostPrizes (Car car, Car best)
{
Car temp = best;
//visit left node
if (car.left != null){
mostPrizes(car.left,best);
}
//check how many prizes
if(car.getPrizes().size() < best.getPrizes().size()){
best = car;
}
//visit right nodes
if (car.right != null ){
mostPrizes(car.right,best);
}
return best;
}}
The mostPrzes
method of yours is not right, because you are not assigning best
of left and right subtrees to the current best
, change it to the code below
public Car mostPrizes (Car car)
{
if(car== null){
return null;
}
Car leftMax= mostPrizes(car.left);
Car rightMax= mostPrizes(car.right);
if(leftMax!=null){
if(car.getPrizes().size()>leftMax.getPrizes().size()){
return node;
}
else{
return leftMax;
}
}
if(rightMax!=null){
if(car.getPrizes().size()>rightMax.getPrizes().size()){
return node;
}
else{
return rightMax;
}
}
return car;
}