Create a new project and class FamilyTree with the following structure: public c
ID: 3541127 • Letter: C
Question
Create a new project and class FamilyTree with the following structure: public class FamilyTree{ public FamilyTree(Tree t); Returns the parent of the given node public String getParent(Node person); Returns the parent of the parent of the given node public String getGrandparentlNode person); Returns all children of the given node public List getChildrenlNode person); Returns all children of the children of the given node public List getGrandchildrenl Node person); { For example, the family where 'Bob' has children 'Jane' and 'Tim', and 'Tim' has daughter 'Kate', can be build like so Tree t = new SimpleTree(); Node bob = new SimpleNodel"Bob"); Node jane = new SimpleNode("Dane"); Node tim = new SimpleNode("Tim"); Node kate = new SimpleNodel"Kate"); t.setRoot(bob); t.insert(bob, jane); t.insert(bob, tim); t.insert(tim, kate); FamilyTree f = new FamilyTree(t); Given this representation, implement the methods above. Return "No parentExplanation / Answer
Hi ,
I have done the implementation of the methods. Hope it Helps :)
import java.util.*;
public class FamilyTree {
public FamilyTree(Tree t){}
public String getParent(Node person)
{
Node n = person.parent;
if(n!=null)
{
return n.name;
}
else
{
return "No Parent exists";
}
}
public String getGrandparent(Node person)
{
Node n = person.parent;
if(n!=null)
{
Node gp = n.parent;
if(gp!=null)
{
return gp.name;
}
else
{
return "No GrandParent exists";
}
}
return "No GrandParent exists";
}
public List<String> getChildren(Node person){
if(person.children.size()==0)
{
return new ArrayList<String>();
}
else
{
List<Node> ns = person.children;
List<String> ss = new ArrayList<String>();
int nval = person.children.size();
for(int i=0;i<nval;i++)
{
ss.add(ns.get(i).name);
}
return ss;
}
}
public List<String> getGrandchildren(Node person){
if(person.children.size()==0)
{
return new ArrayList<String>();
}
else
{
List<Node> ns = person.children;
List<String> ss = new ArrayList<String>();
int nval = person.children.size();
for(int i=0;i<nval;i++)
{
List<Node> chil = ns.get(i).children;
int chilval = chil.size();
if(chilval==0)
{
continue;
}
else
{
for(int j=0;j<chilval;j++)
{
ss.add(chil.get(j).name);
}
}
}
return ss;
}
}
public static void main(String[] args) {
}
}
class Tree
{
Node root ;
}
class SimpleTree extends Tree
{
public void setRoot(Node n)
{
n.isRoot=true;
root = n;
}
public void insert(Node par, Node child)
{
par.children.add(child);
child.parent = par;
}
}
class Node
{
Node parent=null;
List<Node> children=null;
String name;
boolean isRoot;
}
class SimpleNode extends Node
{
public SimpleNode(String S)
{
name =S;
children = new ArrayList<Node>();
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.