我需要生成一棵树,其中一个节点可以有一些特定的子节点,但节点的数量不能在同一分支中重复。
1:5
2:5
3:5
4:5
5:1,2,3,4
Where ':' means that node n can have the children x,y,z,...
The root is 0, has all the possible children, but does not repeat in the tree.
0
/ / | \ \
1 2 3 4 5
| | | | / / \ \
5 5 5 5 1 2 3 4
/ | \ / | \ / | \ / | \
2 3 4 1 3 4 1 2 4 1 2 3
最佳答案
你只需要执行一个从一到五的for循环,并在循环内有一个if来查看子节点是否与你所在的节点(父节点)相同,如果是,则使用继续跳过它。
如果它不能在整个分支中重复,那么您还必须检查祖父节点,实际上是所有祖先节点。您可以在主 for 循环内使用 while 循环来完成此操作。循环直到您检查的祖先节点不为0。在while循环中,您需要将祖先设置为祖先的父节点。
这将“递归”(调用自身),使每个新级别下降,直到特定分支中的所有数字都用完。
伪代码:
void makeTree()
{
addNode(0, null);
}
function node addNode(nodeNumber, parent)
{
nodeCollection nodes;
if (parent != null)
nodes = parent.nodes;
else
nodes = tree.nodes;
node addNode = nodes.add(nodeNumber);
for (int i = 1; i <= 5; i++)
{
bool alreadyexists = false;
node ancestor = addNode;
while (ancestor != null)
{
if (ancestor == childNode)
{
alreadyExists = true;
break;
}
ancestor = ancestor.parent;
}
if (!alreadyExists)
addNode(childNode, addNode);
}
}
关于c# - 如何生成具有重复值的树,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29176642/