递归到迭代程序
Posted
技术标签:
【中文标题】递归到迭代程序【英文标题】:Recursion to iterative program [duplicate] 【发布时间】:2018-09-25 06:41:31 【问题描述】:我试图将递归程序转换为非递归程序。程序的目的是遍历数据结构。
请在下面找到数据结构
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。
有人可以帮我编写上述程序的迭代版本吗?
【问题讨论】:
class Node() ...
这在java中正确吗?
是的,我的***类是 RecursiveTraversal 所有其他类都包含在同一个文件中,我能够执行程序获取输出,在浏览器中输入时可能会出错,但大多数情况下它应该运行小改动。
你有很多编译错误。修复并等待帮助。没有人不必解决你的错误。您的问题是关于迭代的逻辑,但代码不起作用。
第 1 步:认识到您的递归方法是 Depth-First Search。 --- 第 2 步:进行网络搜索以了解如何在没有递归的情况下执行此操作:non-recursive depth first search
删除了所有编译错误,请立即检查
【参考方案1】:
要使其迭代,只需使用 while 循环或 for 循环。
比如:
while(getLeafNode() != null)
// etc
还有:
prvate int leafNodeValue;
可能应该是私有的而不是私有的?
【讨论】:
以上是关于递归到迭代程序的主要内容,如果未能解决你的问题,请参考以下文章