Need a search method for my tree (n-ary tree)

I wrote this tree class for the family

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

its n-ary tree, each of which node can have from 0 to n children

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

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;
}

}
+2
source share
1 answer

Check out Tree Traversal algorithms. This article describes them pretty well (using recursion and deletion) Here is one way to move 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 go through the whole tree, do the following:

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

, . , , StackOverFlow.

+3

All Articles