在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()方法中创建了一个简单的树结构,并通过递归查询找到了指定节点。
上一篇:java多线程如何查询数据库
下一篇:idea加载依赖很慢怎么解决
java









