Menu
Question Index
...


Write a program to get the parent of a person. If the person name is not present or if the person is the top most person, then return null.

Assume the following family hierarchy.

Rajeswara Rao
+--Suresh
|  +--Mahesh
|  +--Lakshmi
+--Ramesh
|  +--Srinivas
|     +--Kamala
|     +--Raj

Input (String) Output (Person)
Lakshmi Suresh
Kamala Srinivas
Ramesh Rajeswara Rao
Rajeswara Rao null
Anamika null

class FindParent

{    public static void main(String s[])
    {
        Person rajeswaraRao = new Person("Rajeswara Rao");
        Person suresh = new Person("Suresh");
        Person ramesh = new Person("Ramesh");
        rajeswaraRao.children.add(suresh);
        rajeswaraRao.children.add(ramesh);
        Person mahesh = new Person("Mahesh");
        Person lakshmi = new Person("Lakshmi");
        suresh.children.add(mahesh);
        suresh.children.add(lakshmi);
        Person srinivas = new Person("Srinivas");
        ramesh.children.add(srinivas);
        Person kamala = new Person("Kamala");
        Person raj = new Person("Raj");
        srinivas.children.add(kamala);
        srinivas.children.add(raj);
        Person parent = getParent(rajeswaraRao, "Lakshmi");
        System.out.println("The parent of Lakshmi is " + parent);

    }


public static Person getParent(Person root, String name) {
//Write code here to find the parent of the person with the given name
}
}
class Person {

String name;
List<Person> children = new ArrayList<Person>();

public Person(String name) {
this.name = name;
}

public String toString() {
return name;
}
}

Doubts

Problems

Topic: Collection Framework In Java

Read this topic
Take test on this topic

0
Wrong
Score more than 2 points

© meritcampus 2019

All Rights Reserved.

Open In App