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;
}
}
这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。
V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。
V2EX is a community of developers, designers and creative people.