在非二进制的树中搜索

时间:2011-05-25 14:03:52

标签: java binary-search-tree

嘿伙计们, 我创建了一个不是二叉树的树。现在,我想要的是搜索一个元素。主要的是以下内容:由于与二叉树相比没有比较机会,我必须找到一些其他方法来实现代码。这就是我的想法:

public TreeNode<City> search(City parent, TreeNode<City> t){
//As you guess, City class is irrelevant to the issue, I have no problem with City class.
    if (t.getCity().equals(parent)) {
        return t;
    }
    else if (t.hasLeftChild()){
        search(parent,t.getLeftChild());
    }
    else if(t.hasNextSibling()){
        search(parent,t.getNextSibling());
    }
    else//Since I know that case will never happen, the returned value is unimportant
        return t;
    }

当然,该代码不起作用。困难的部分是我必须在找到它后立即返回我正在搜索的值。然而,如果我找不到它,我仍然需要返回一些东西。我怎么会这样做?

2 个答案:

答案 0 :(得分:0)

首先,您需要(以某种方式)使用递归调用search()返回的值 - 可能是return

public TreeNode<City> search(City parent, TreeNode<City> t){
    if (t.getCity().equals(parent)) {
        return t;
    }
    else if (t.hasLeftChild()){
        return search(parent,t.getLeftChild());
    }
    else if(t.hasNextSibling()){
        return search(parent,t.getNextSibling());
    }
    return null;
}

答案 1 :(得分:0)

您正在寻找的递归函数的元代码

public TreeNode<City> search(City parent, TreeNode<City> t){
    if (t.getCity().equals(parent)) {
        return t;
    }

    if (t.hasLeftChild()) {
        if (tmp = search(parent,t.getLeftChild())) {
            return tmp;            
        }
    }

    if (t.hasnextSibling()) {
        if (tmp = search(parent,t.getnextSibling())) {
            return tmp;            
        }
    }

    return false;
}
相关问题