I was trying to convert recursive program to non recursive program. Purpose of the program is traversal of the data structure.
Please find below data structure
class Node {
}
class LeafNode extends Node {
private int leafNodeValue;
public LeafNode (int leafNodeValue) {
this.leafNodeValue= leafNodeValue;
}
public int getLeafNodeValue() {
return leafNodeValue;
}
public void setLeafNodeValue(int leafNodeValue ) {
this.leafNodeValue = leafNodeValue;
}
}
class NonLeafNode extends Node {
private List<Node> nodeList = new ArrayList<>();
public List<Node> getNodeList() {
return nodeList ;
}
public void setNodeList(List<Node> nodeList) {
this.nodeList = nodeList;
}
}
Here is my recursive node traversal class that I'm having trouble rewriting non-recursively.
Recursive Traversal Class
public class RecursiveTraversal {
public static void main (String[] args ) {
NonLeafNode node1 = new NonLeafNode();
NonLeafNode node2 = new NonLeafNode();
node2.getNodeList().add(new LeafNode(1));
NonLeafNode node3 = new NonLeafNode();
node3.getNodeList().add(new LeafNode(2));
node2.getNodeList().add(node3);
NonLeafNode node4 = new NonLeafNode();
node4.getNodeList().add(new LeafNode(3));
node1.getNodeList().add(node2);
node1.getNodeList().add(node4);
node1.getNodeList().add(new LeafNode(4));
for (Node nodeItem : node1.getNodeList())
traverse(nodeItem);
}
public static void traverse (Node node) {
if (node instanceof LeafNode)
System.out.println(" Leaf Node " + ((LeafNode) node).getLeafNodeValue());
else if (node instanceof NonLeafNode)
for (Node nodeItem: ((NonLeafNode) node).getNodeList())
traverse(nodeItem);
}
}
Output of the program should be 1,2,3,4.
Can someone please help me to write iterative version of above program?