### 题目：

[
[1,null,3,2],
[3,2,null,1],
[3,1,null,null,2],
[2,1,3],
[1,null,2,null,3]
]

1         3     3      2      1
\       /     /      / \      \
3     2     1      1   3      2
/     /       \                 \
2     1         2                 3

### 解题：

/**
* Definition for a binary tree node.
* public class TreeNode {
*     public int val;
*     public TreeNode left;
*     public TreeNode right;
*     public TreeNode(int x) { val = x; }
* }
*/
public class Solution {public IList<TreeNode> GenerateTrees(int n)
{
var preResult = new List<TreeNode>();
if (n == 0)
{
return preResult;
}

for (int i = 1; i <= n; i++)
{
var currentResult = new List<TreeNode>();

foreach (var node in preResult)
{
//放在顶点
{
left = TreeCopy(node)
};

//放在上一次结果的右顶点
//count用来记录下一次遍历到哪个顶点
int count = 1;
while (count > 0)
{
var newTreeNode = TreeCopy(node);
var targetNode = newTreeNode;
var newRigthNode = new TreeNode(i);

for (int j = 1; j < count; j++)
{
targetNode = targetNode.right;
}
if (targetNode != null)
{
var tempNode = targetNode.right;
targetNode.right = newRigthNode;
newRigthNode.left = tempNode;
count++;
}
else
{
count = -1;
}

}

preResult = currentResult;
}
}

return preResult;
}

private TreeNode TreeCopy(TreeNode treeNode)
{
if (treeNode == null)
{
return null;
}
var result = new TreeNode(treeNode.val)
{
left = TreeCopy(treeNode.left),
right = TreeCopy(treeNode.right)
};
return result;
}
}

03-25 7061
05-25 237

02-02 945
07-27 48
03-23 24
03-23 128