二叉树搜索返回最高编号

时间:2017-04-29 14:13:38

标签: java algorithm recursion binary-tree binary-search-tree

我正在努力寻找奖品数量最多的汽车。我访问树的每个节点,我得到数组大小并将其与每个节点进行比较。但是我似乎无法返回具有最高值的节点。任何人都可以查看我的代码并指出它有什么问题吗? 此外,我不确定我是否正确地从递归方法mostPrizes返回它。

My tree

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;
  }}

1 个答案:

答案 0 :(得分:0)

您的mostPrzes方法不对,因为您没有将best左右子树分配给当前best,请将其更改为下面的代码

    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;
    }