【问题标题】:need a search method for my tree(n-ary tree) [closed]需要我的树的搜索方法(n-ary 树)[关闭]
【发布时间】:2012-07-01 19:31:15
【问题描述】:

我已经为家谱编写了这个树类

现在我需要一种搜索​​方法来查找树中的节点

它是一个 n-ary 树,每个节点可以有 0 到 n 个子节点

搜索方法可以搜索一个节点或两个名字,包括节点名和他/她的父亲名字

请帮帮我

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

}

【问题讨论】:

标签: java search tree


【解决方案1】:

看看树遍历算法。这个article 很好地涵盖了它们(使用递归和出队) 这是遍历树的一种方法

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

要遍历所有树,请执行以下操作:

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

请注意,此方法使用递归。如果你的树很大,那么我建议你改用队列,因为递归可能会导致 StackOverFlow 异常。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-06-02
    • 1970-01-01
    • 2014-04-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多