Cognzant Technology Solutions Interview Question for Dev Leads
- 0of 0 votes
AnswerHi Implemented this sample code for N-ary postOrder Traversal.
- sunny346 October 11, 2016 in India
Now i want to throw error statement id the parent node is dependent on child.
Can some one help
package dependencyAlgorithm;
import java.util.*;
public class Dependency
{
class MainRule
{
String ruleName;
ArrayList<MainRule> subrule;
public MainRule(String name)
{
this.ruleName=name;
subrule=new ArrayList<>();
}
}
public static void postOrder(MainRule rootRule)
{
Stack<List<MainRule>> stack = new Stack<>();
MainRule rule = rootRule;
List<MainRule> list = null;
while (true)
{
if(rule != null)
{
list = rule.subrule;
for(int i=0;i<list.size();i++)
{
if(rule.ruleName == list.get(i).ruleName)
break;
}
rule = null;
if(list!=null && list.size()>0)
{
//push the list in the stack (do not modify original tree structure).
stack.push(new ArrayList<>(list));
//get first item from this list
rule = stack.peek().get(0);
System.out.print("\n1 ListSize: "+list.size());
}
}
else if (!stack.isEmpty())
{
System.out.print("\n2 \n");
list = stack.pop();
System.out.print("\n2 ListSize: "+list.size());
rule = list.remove(0); //shift left
System.out.print("\n2.1 ListSize: "+list.size());
System.out.print("\n"+rule.ruleName+" ");
rule = null;
if(list.size()>0)
{
System.out.print("\n3 ListSize "+list.size());
stack.push(list); //push back remaining list into stack
rule = stack.peek().get(0); //prepare for next iteration
}
}
else
break;
}
System.out.println(rootRule.ruleName);
}
/*
Fml001
/ | \
/ | \
/ | \
Fml002 C001_Base Tot001
/ / | \
/ / | \
Fml003 Fml004 R001_Base R001_TxPat
/
/
Tot002
\
\
C001_TxPat
*/
public void createBinaryTree()
{
MainRule rootRule;
MainRule Fml001 =new MainRule("Fml001");
MainRule Fml002=new MainRule("Fml002");
MainRule Fml003=new MainRule("Fml003");
MainRule Fml004=new MainRule("Fml004");
MainRule C001_Base=new MainRule("C001_Base");
MainRule R001_Base=new MainRule("R001_Base");
MainRule Tot001=new MainRule("Tot001");
MainRule Tot002 =new MainRule("Tot002");
MainRule R001_TxPat =new MainRule("R001_TxPat");
MainRule C001_TxPat =new MainRule("C001_TxPat");
rootRule=Fml001;
rootRule.subrule.add(Fml002);
rootRule.subrule.add(C001_Base);
rootRule.subrule.add(Tot001);
Fml002.subrule.add(Fml003);
C001_Base.subrule.add(Fml004);
C001_Base.subrule.add(R001_Base);
C001_Base.subrule.add(R001_TxPat);
R001_Base.subrule.add(Tot002);
Tot002.subrule.add(C001_TxPat);
postOrder(rootRule);
}
public static void main(String[] args)
{
Dependency dependency=new Dependency();
// Creating a tree structure
System.out.println("Path Traversed:");
dependency.createBinaryTree();
}
}| Report Duplicate | Flag | PURGE
Cognzant Technology Solutions Dev Lead Trees and Graphs
Interview Type: Written Test
- sunny346 October 11, 2016