预订在二叉搜索树中遍历

时间:2017-12-11 05:40:20

标签: java traversal

我遇到了问题并且无法弄清楚为什么我的方法在找到对象时没有返回对象?它首先以递归方式遍历树的左侧,然后是右侧。找到客户后会显示println语句,但return customer始终为null。我在这里做错了什么?

    public Customer lookUpCustomer(String lastName, String firstName) {

    Customer customer;
    Customer foundCustomer = null;

    if (left != null) {

        customer = (Customer) left.getItem();

        if(customer.getLastName().equals(lastName) && customer.getFirstName().equals(firstName)) {
            System.out.println("Found customer: " + customer.toString());
            return customer;
            //foundCustomer = customer;             
        }
        left.lookUpCustomer(lastName, firstName);
    }
    if (right != null) {

        customer = (Customer) right.getItem();

        if(customer.getLastName().equals(lastName) && 
       customer.getFirstName().equals(firstName)) {
            System.out.println("Found customer: " + customer.toString());
            return customer;
            //foundCustomer = customer;         
        }   
        right.lookUpCustomer(lastName, firstName);
    }

    return null;
}

1 个答案:

答案 0 :(得分:4)

因为您总是返回null来第一次调用lookUpCustomer。此外,您不会通过lookUpCustomer方法的递归调用保存返回值。

要解决此问题,请返回找到的节点。您可以按以下方式更改代码:

public Customer lookUpCustomer(String lastName, String firstName) {

    Customer customer;
    Customer foundCustomer = null;

    if (left != null) {

        customer = (Customer) left.getItem();

        if(customer.getLastName().equals(lastName) && customer.getFirstName().equals(firstName)) {
            System.out.println("Found customer: " + customer.toString());
            return customer;
            //foundCustomer = customer;             
        }
        foundCustomer = left.lookUpCustomer(lastName, firstName);
    }
    if (foundCustomer==null && right != null) {

        customer = (Customer) right.getItem();

        if(customer.getLastName().equals(lastName) && 
       customer.getFirstName().equals(firstName)) {
            System.out.println("Found customer: " + customer.toString());
            return customer;
            //foundCustomer = customer;         
        }   
        foundCustomer  = right.lookUpCustomer(lastName, firstName);
    }

    return foundCustomer;
}