need a search method for my tree(n-ary tree) [closed]

梦想的初衷 提交于 2019-12-12 17:12:27

问题


i have written this tree class for a familytree

now i need a search method to find a node in my tree

its a n-ary tree that each node can have 0 to n children

the search method can search for a node or for two names includes node name and his/her father name

plz help me

public class FamilyNode {
 public String name;
 public String sex;
 public FamilyNode Father;
 public FamilyNode Mother;
 public FamilyNode Spouse=null;
 public String status="alive";
 public int population;
 public ArrayList<FamilyNode> children=new ArrayList<FamilyNode>() ;


public FamilyNode(String name1,String sex1){
this.name=name1;
this.sex=sex1;
this.population=this.children.size()+1;
}
public void SetParents(FamilyNode father,FamilyNode mother){
    this.Father=father;
    this.Mother=mother;
    }
public void SetHW(FamilyNode HW){
    this.Spouse=HW;
}
public void AddChild(FamilyNode child){
    child.SetParents(this.Father, this.Spouse);
    this.children.add(child);
    this.Spouse.children.add(child);
}

public int Number (){
   int number_of_descendants = this.population;
   if(this.Spouse!=null) number_of_descendants++;
for(int index = 0; index < this.children.size(); index++)
number_of_descendants = number_of_descendants+ this.children.get(index).Number();
return number_of_descendants;
}

}

回答1:


Have a look at Tree Traversal algorithms. This article covers them pretty well (using recursion and dequeues) Here is one way of traversing your tree

public class FamilyNode {
    // ...
    // ...
    public void traverseNode(){
       if(name.equals("NameWeAreLookingFor")){
          // We found a node named "NameWeAreLookingFor"
          // return here if your are not interested in visiting children
       } 
       for(FamilyNode child : node.children){
            child.traverseNode();
       }
    }
}

To traverse all your tree, do the following:

FamilyNode root = ...;
root.traverseNode();

Note that this method is using recursion. If your tree is very big then I suggest you go for using queues instead as recursion might end up in a StackOverFlow exception.



来源:https://stackoverflow.com/questions/11275817/need-a-search-method-for-my-treen-ary-tree

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!