无限递归

时间:2013-04-25 23:34:28

标签: java recursion

我有以下代码:

public void generateTree(Node myNode) {
    for(int i = 1; i <= 6; i++) {
        //Creating child node
        Node child = new Node();

        //Setting new Depth
        child.setDepth(myNode.getDepth()+1);

        //Adding node to tree
        myTree.add(child);

        //If the game isn't over and we're not reached the maximum depth, recurse
        if(!isGameOver() && child.getDepth() < MAX_DEPTH)
            generateTree(child);
    }
}

基本上MAX_DEPTH是一个整数,表示我想要探索游戏中移动树的最大深度,getDepth()返回作为参数提交的节点的深度,setDepth设置新节点的深度。 / p>

出于某种原因,它似乎会产生无限递归但是......有什么建议吗?

1 个答案:

答案 0 :(得分:0)

你的问题不是无限递归。它可能是别的东西。这段代码适合我 -

import java.util.ArrayList;
import java.util.List;


public class Node 
{

    private int depth;

    public static final int MAX_DEPTH = 2;

    private static List<Node> myTree = new ArrayList<Node>(); // for testing purposes

    public void generateTree(Node myNode) {
        for(int i = 1; i <= 6; i++) {
            //Creating child node
            Node child = new Node();

            //Setting new Depth
            child.setDepth(myNode.getDepth()+1);

            //Adding node to tree
            myTree.add(child);

            //If the game isn't over and we're not reached the maximum depth, recurse
            if(child.getDepth() < MAX_DEPTH)
                generateTree(child);
        }
    }

    public static void main(String [] args)
    {
        Node node = new Node();

        Node myNode = new Node();
        myNode.setDepth(0);

        node.generateTree(myNode);

        System.out.println(myTree.size());

    }

    public int getDepth() {
        return depth;
    }

    public void setDepth(int depth) {
        this.depth = depth;
    }

}

我得到的输出是

42