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
|  +--Mahesh
|  +--Lakshmi
|  +--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");
        Person mahesh = new Person("Mahesh");
        Person lakshmi = new Person("Lakshmi");
        Person srinivas = new Person("Srinivas");
        Person kamala = new Person("Kamala");
        Person raj = new Person("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) { = name;

public String toString() {
return name;



Topic: Collection Framework In Java

Read this topic
Take test on this topic

Score more than 2 points

© meritcampus 2019

All Rights Reserved.

Open In App