怎么了?试图建立一棵树

时间:2010-02-11 20:20:52

标签: c# tree recursion

调用函数MakeTree(4, gameboard)无法正常工作,它只打印出第一个validMove-Nodes。我做错了什么?

private Move MakeTree(int depth, Board b)
    {

        Move Tree = GenerateValidMoves(b, b.MyLocation);
        if (depth == 0) return Tree;
        foreach (TreeNode<Move> Child in Tree.Children)
        {
            Board temp = Board.ApplyMove(b, Child.Value);
            Child.Children.Add(MakeTree(depth-1, temp));
        }
        return Tree;
    }

给我以下输出:

[S 1|1, D: 2|1 (East)] Depth=1, Children =1
[] Depth=2, Children =0
[S 1|1, D: 1|2 (South)] Depth=1, Children =1
[]Depth=2, Children =0

显示每个生成的内联树为我提供以下输出:

[S 1|1, D: 2|1 (East)] Depth=1, Children =0
[S 1|1, D: 1|2 (South)] Depth=1, Children =0
[S 2|1, D: 3|1 (East)] Depth=1, Children =0
[S 2|1, D: 2|2 (South)] Depth=1, Children =0
[S 3|1, D: 4|1 (East)] Depth=1, Children =0
[S 3|1, D: 3|2 (South)] Depth=1, Children =0
[S 4|1, D: 5|1 (East)] Depth=1, Children =0
[S 4|1, D: 4|2 (South)] Depth=1, Children =0
[S 4|1, D: 5|1 (East)] Depth=1, Children =0
...

显然它只访问第一个生成的节点。

1 个答案:

答案 0 :(得分:0)

你需要对MakeTree进行递归。尝试使用yield return语法和IEnumerable,它会让你的生活更轻松