数组树找到父母和他们的父母以及到根的最短路径
我想找到从孩子到他的父母,到祖父母,最后到根的最短路线。
例如,输入 0 0 0 1 2
表示:
input[1] parent is 0 (route = 1)
input[2] also has parent 0 (route = 1)
input[3] has parent 1 which has parent 0 (route = 2)
input[4] has parent 2 which has parent 0 (route = 2)
到目前为止的代码:
创建名为 targetNodes
的数组,其中包含 0 0 0 1 2
,
System.out.print( "0 " );
for ( int x = 1; x < arrayLength; x++ )
{
int depth = 1;
int parent = 0;
while ( targetNodes[x] != 0 )
{
depth++;
targetNodes[x] = targetNodes[ targetNodes[x] ] ;
}
// output shortest path from node to root for every node
System.out.print( depth + " " );
}
System.out.print("\n");
我的示例有效,输入:0 0 0 1 2
,它打印:0 1 1 2 2
, 但对于输入:0 0 1 2 1 4
,它会打印出:0 1 2 2 2 2
,而正确的输出是:0 1 2 3 2 3
不确定我做错了什么,我猜这是逻辑
I want to find the shortest route from a child, to his parent, to grandparent and in the end the root.
For example, input 0 0 0 1 2
, means that:
input[1] parent is 0 (route = 1)
input[2] also has parent 0 (route = 1)
input[3] has parent 1 which has parent 0 (route = 2)
input[4] has parent 2 which has parent 0 (route = 2)
Code so far:
Array is created called targetNodes
which contains 0 0 0 1 2
,
System.out.print( "0 " );
for ( int x = 1; x < arrayLength; x++ )
{
int depth = 1;
int parent = 0;
while ( targetNodes[x] != 0 )
{
depth++;
targetNodes[x] = targetNodes[ targetNodes[x] ] ;
}
// output shortest path from node to root for every node
System.out.print( depth + " " );
}
System.out.print("\n");
My example works and with input: 0 0 0 1 2
it prints: 0 1 1 2 2
,
but for input: 0 0 1 2 1 4
it prints out: 0 1 2 2 2 2
when the correct output would be: 0 1 2 3 2 3
Not sure what I am doing wrong, I would guess it's the logic
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
其实很简单。最困难的部分是转换单元测试的数据,以便可以有效地输入它们。
It's actually pretty simple. The hardest part was to convert the data for the unit tests, so that they can be efficiently typed.