如何生成具有重复值的树
How can I generate a tree with duplicate values
我需要生成一棵树,其中一个节点可以有一些特定的children,但是节点的编号不能在同一个分支中重复。
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循环里面,你需要设置祖先为祖先的父节点。
这将 "recurse"(调用自身)使每个新级别下降,直到特定分支中的所有数字都用完。
伪代码:
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);
}
}
我需要生成一棵树,其中一个节点可以有一些特定的children,但是节点的编号不能在同一个分支中重复。
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循环里面,你需要设置祖先为祖先的父节点。
这将 "recurse"(调用自身)使每个新级别下降,直到特定分支中的所有数字都用完。
伪代码:
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);
}
}