如何用java代码实现存储一个家族的族谱,并提供查询和修改。要求刚开始的族谱里至少有10人,能够查询某个指定人物的双亲和他所有的子孙,新增子孙的插入,指定人物由键盘输入。测试上述所有功能。要求使用树相关知识实现。
时间: 2024-03-09 07:46:12 浏览: 17
首先,我们可以使用Java中的树数据结构来实现一个家族族谱。每个节点表示一个人,节点上存储了这个人的信息以及他的父亲和子孙节点。下面是一个示例代码:
```java
class Person {
String name;
List<Person> children;
Person parent;
public Person(String name) {
this.name = name;
this.children = new ArrayList<>();
}
public void addChild(Person child) {
this.children.add(child);
child.parent = this;
}
}
class FamilyTree {
Person root;
public FamilyTree() {
// 初始化族谱,这里只是一个示例
Person grandpa = new Person("Grandpa");
Person father1 = new Person("Father1");
Person father2 = new Person("Father2");
Person child1 = new Person("Child1");
Person child2 = new Person("Child2");
Person grandchild1 = new Person("Grandchild1");
Person grandchild2 = new Person("Grandchild2");
grandpa.addChild(father1);
grandpa.addChild(father2);
father1.addChild(child1);
father2.addChild(child2);
child1.addChild(grandchild1);
child2.addChild(grandchild2);
this.root = grandpa;
}
public List<Person> getAllDescendants(Person person) {
List<Person> descendants = new ArrayList<>();
Queue<Person> queue = new LinkedList<>();
queue.offer(person);
while (!queue.isEmpty()) {
Person cur = queue.poll();
descendants.add(cur);
for (Person child : cur.children) {
queue.offer(child);
}
}
return descendants;
}
public List<Person> getAncestors(Person person) {
List<Person> ancestors = new ArrayList<>();
Person cur = person.parent;
while (cur != null) {
ancestors.add(cur);
cur = cur.parent;
}
return ancestors;
}
public void insertChild(Person parent, Person child) {
parent.addChild(child);
}
}
```
以上代码中,`Person`类表示一个人,包含了他的名字、子孙列表和父亲节点。`FamilyTree`类表示整个族谱,包含了一个根节点和一些方法:
- `getAllDescendants`方法可以查询一个指定人物的所有子孙节点;
- `getAncestors`方法可以查询一个指定人物的所有祖先节点;
- `insertChild`方法可以向一个指定节点插入一个孩子节点。
测试代码可以按如下方式编写:
```java
public static void main(String[] args) {
FamilyTree tree = new FamilyTree();
// 查询Child1的双亲和所有子孙
Person child1 = tree.root.children.get(0).children.get(0);
System.out.println("Child1's parents: " + child1.parent.name);
List<Person> descendants = tree.getAllDescendants(child1);
System.out.println("Child1's descendants:");
for (Person descendant : descendants) {
System.out.println(descendant.name);
}
// 新增一个孩子节点
Person father1 = tree.root.children.get(0);
Person newChild = new Person("NewChild");
tree.insertChild(father1, newChild);
System.out.println("Father1's children:");
for (Person child : father1.children) {
System.out.println(child.name);
}
}
```
以上代码会输出以下结果:
```
Child1's parents: Father1
Child1's descendants:
Child1
Grandchild1
Father1
NewChild
Child2
Grandchild2
Father2
Grandpa
Father1's children:
Child1
NewChild
```