java - Java树,递归返回父节点
问题描述
我正在处理一些关于从树中返回父节点的任务。
树看起来像这样:
1
/ \
2 3
/ /
4 5
/ \
6 7
它有一些限制,即类节点没有可以返回父节点的方法。所以我们需要创建自己的方法来获取父节点。这是我的方法:
public Node getParentNode(int idChild, Node pParent) {
List<Node> child;
List<Node> gChild;
if (pParent == null)
{
child = root.getChildren();
} else {
child = pParent.getChildren();
}
Node nParent = null;
if (child != null) {
for (Node c : child) {
if (c.getId() == idChild) {
nParent = c;
break;
} else {
return getParentNode(idChild, c);
}
}
}
return nParent;
}
不知何故,它可以检索 id 为 4 的节点的父节点,即 id 为 2 的节点。但是在检索 id 为 5、6 和 7 的节点的父节点时,它不起作用。所以基本上它只适用于 id 为 2、3 和 4 的节点。
有人可以指出我在递归或循环中缺少什么吗?因为我不是很擅长。
解决方案
问题就在这里
return getParentNode(idChild, c);
您不应该只是按原样返回此调用的结果。如果您要搜索的节点不在该子树中怎么办。只有当它返回非空结果时才应该返回(否则for循环不会循环到下一个子节点)
仅当您在递归调用中找到父节点时才返回。
此外,块中的 return 语句存在错误if
。您应该返回对父节点而不是当前子节点的引用。
{
....
if (child != null) {
for (Node c : child) {
gChild = c.getChildren(); //Btw this is just dead store
if (c.getId() == idChild) {
return pParent; //You want to return the parent not the current node.
} else {
nParent = getParentNode(idChild, c);
if (nParent != null) {
return nParent;
}
}
}
}
return null; //Node (idChild) not found in this subtree
}
推荐阅读
- python - 添加字体文件进行设置
- flutter - 如何在 Flutter 中使用 firstWhere 导航到另一个屏幕
- javascript - 如何在 Javascript 中使用 Kuromoji.js
- python - 在 ctypes 中使用指向日期的指针 (DATE * pValnDate)
- reactjs - 设置加载状态后才调用API
- javascript - Node JS Https.Request() 方法 req,res on,data,end 事件不起作用
- android - 当我运行我的应用程序时,为什么我的小部件没有正确定位?
- python - simple-youtube-api 中的 storage_path 应该如何?
- reactjs - 将 Svelte 组件作为道具传递
- angular - Angular 11 中的 Fancybox 幻灯片自动启动