在Java中递归查询父子节点可以使用递归算法来实现。以下是一个简单的示例代码:
public class TreeNode {
private String value;
private List<TreeNode> children;
public TreeNode(String value) {
this.value = value;
children = new ArrayList<>();
}
public void addChild(TreeNode child) {
children.add(child);
}
public TreeNode findChild(String value) {
for (TreeNode child : children) {
if (child.value.equals(value)) {
return child;
} else {
TreeNode found = child.findChild(value);
if (found != null) {
return found;
}
}
}
return null;
}
public static void main(String[] args) {
TreeNode root = new TreeNode("A");
TreeNode b = new TreeNode("B");
TreeNode c = new TreeNode("C");
TreeNode d = new TreeNode("D");
TreeNode e = new TreeNode("E");
root.addChild(b);
root.addChild(c);
b.addChild(d);
b.addChild(e);
TreeNode result = root.findChild("E");
if (result != null) {
System.out.println("找到了节点:" + result.value);
} else {
System.out.println("未找到指定节点");
}
}
}
在上面的代码中,我们定义了一个TreeNode
类来表示树节点,其中包含一个值和一个子节点列表。通过findChild()
方法来递归查询子节点,如果找到则返回该子节点,如果没有找到则返回null
。在main()
方法中创建了一个简单的树结构,并通过递归查询找到了指定节点。
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,请发送邮件至 55@qq.com 举报,一经查实,本站将立刻删除。转转请注明出处:https://www.szhjjp.com/n/958564.html