对递归算法理解不深,想实现搜索树形结构的某节点,并返回该节点。下面的写法不对呀
public class Test { public static void main(String[] args) { Node root = createTree(); Node node = searchNode(root, "K"); System.out.println("==>" + node); } private static Node searchNode(Node root, String name) Node node = null; for (int i = 0; i < root.getChildren().size(); i++) { Node child = root.getChildren().get(i); if (child.getName().equals(name)) { return child; } node = searchNode(child, name); } return node; } private static class Node { private String name; private List<Node> children; public Node(String name) { this.name = name; this.children = new ArrayList<>(); } public String getName() { return name; } public List<Node> getChildren() { return children; } public void addChild(Node child) { this.children.add(child); } } private static Node createTree() { Node nodeA = new Node("A"); Node nodeB = new Node("B"); Node nodeC = new Node("C"); Node nodeD = new Node("D"); Node nodeE = new Node("E"); Node nodeF = new Node("F"); Node nodeG = new Node("G"); Node nodeH = new Node("H"); Node nodeI = new Node("I"); nodeA.addChild(nodeB); nodeA.addChild(nodeC); nodeB.addChild(nodeD); nodeB.addChild(nodeE); nodeC.addChild(nodeF); nodeC.addChild(nodeG); nodeC.addChild(nodeH); nodeE.addChild(nodeI); return nodeA; } }