以递归方式在未排序的树中搜索

时间:2015-06-29 17:05:32

标签: java algorithm data-structures tree

我试图搜索树中的元素e,但是您可以看到我的搜索(位置,E)没有返回位置。但是,当我添加"返回null;"在方法结束时。它仅在我查找的位置位于其父节点的最左侧子节点时才起作用,否则返回null。如何让它保持工作直到它到达树的末尾?

public Position<E> search(E e) {
    return search(root(), e);
}

public Position<E> search(Position<E> p, E e) {
    if(p.getElement().equals(e))
        return p;
    for(Position<E> c: children(p))
            return search(c, e);
}

2 个答案:

答案 0 :(得分:3)

我认为问题出现在这个循环中:

for(Position<E> c: children(p))
        return search(c, e);

想象一下,您要搜索的元素位于节点的第二个子节点而不是第一个节点。使用上面的代码,在循环的第一次迭代中,您将递归地探索返回false的第一个子节点,然后立即返回false而没有机会探索第二个子节点。换句话说,您的方法只会查看第一个孩子,因此可能找不到您要查找的内容。

要解决此问题,请尝试重写代码:

if(p.getElement().equals(e))
    return p;

for(Position<E> c: children(p)) {
    Position<E> result = search(c, e);
    if (result != null) return result;
}
return null;

这使得每个子树中的递归调用。如果任何一个调用都找不到该元素,那很好 - 你只需继续下一个。如果任何一个调用确实找到了该元素,则返回它。如果没有调用找到该元素,则返回null以指示失败。

希望这有帮助!

答案 1 :(得分:1)

您需要跟踪每个子树及其返回值。尝试以下内容:

global class Industry_Mappings Implements Schedulable {
    Public List < Lead > DisplayIndLeads;
    global void execute(SchedulableContext sc) {

        DisplayIndLeads = new List < Lead > ();
        DisplayIndLeads = [select Industry, Sub_Industry__c from Lead where Sub_Industry__c = null and Industry < > Null and IsConverted < > True];

        //This will create a little efficenty with the for loops
        Integer skip = 0;
        Integer i = 0;

        //Advertising and Marketing
        List < string > AdvertisingAndMarketing = new List < string > {
            'Design', 'Graphic Design', 'Market Research'
        };


        //List for looping
        List < lead > leadstoupdate = new List < Lead > {};

        //This starts the Loop for the leads
        for (Lead ld : DisplayIndLeads) {
            //lead l = (Lead)ld;
            //leadstoupdate.size();

            //Advertising and Marketing
            if (skip == 0) {
                for (string AnM : AdvertisingAndMarketing) {
                    if (ld.Industry == AnM) {
                        ld.Sub_Industry__c = ld.Industry;
                        ld.Industry = 'Advertising and Marketing';
                        skip = 99;
                        leadstoupdate.add(ld);
                    }
                }
            }

            System.debug('***** What is in leadstoupdate: ' + leadstoupdate);
            update leadstoupdate;
        }
    }
}

谢谢,

由里

相关问题