简体   繁体   中英

Java find the route of seeking node in a tree

public List<Person> getDiseaseRouteTo(Person c){

    if(this.contains(c)){
        if(root == c){
            route.add(c);
        }
        else if(root != c){
            route.add(root);
            for(DiseaseTree dt: children){
                if(dt.contains(c)){
                    route.add(dt.root);
                    dt.getDiseaseRouteTo(c);

                }
            }
        }
        return route;
    }
    return null; 
}

The constructor is a tree constructor named DiseaseTree which contain a root node and a Children set. The children set is a DiseaseTree set. I am supposed to find the route of seeking one node. For example, I have an existed tree named ddtt and I want to find the route to find node c in this tree. ddtt.getDiseaseroute(c) will get a list to find node c. like[A, B, C] if tree is like A --B ----C

I used recursion to realize that. But it can't have complete route. I don't know what is going on and totally confused.

you are adding the root twice to the route list, once on the line "route.add(root);" and the second time when you go over his children "route.add(dt.root);". you don't need to add it twice. Also next time try to debug it with a simple input and see what is going on.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM