递归到迭代程序

时间:2018-09-25 06:41:32

标签: java recursion

我试图将递归程序转换为非递归程序。该程序的目的是遍历数据结构。

请在下面找到数据结构

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;
    }
}

这是我的递归节点遍历类,无法递归重写。

递归遍历类

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);
    }
}

程序的输出应为1,2,3,4。

有人可以帮我编写上述程序的迭代版吗?

1 个答案:

答案 0 :(得分:0)

要进行迭代,只需使用while循环或for循环。

类似这样:

while(getLeafNode() != null) {
  // etc
}

也:

prvate int leafNodeValue;

可能应该是私有的而不是私有的?