楼主第二题能用你的样例测一下这个代码么,我用你的代码跑了一下,和我的输出是相同的,不知道错了哪个 样例。
import java.util.*; class Node { String name; int parent; ArrayList<Node> children; Node() { this.children = new ArrayList<>(); } } public class Mainb { public static void dfs(Node nodes, String s) { if (nodes.children.size() == 0) return; for (int i = 0; i < nodes.children.size(); i++) { Node node = nodes.children.get(i); String s1; if (i != nodes.children.size() - 1) s1 = s + "|"; else s1 = s + "`"; System.out.println(s1 + "-- " + node.name); if (node.children.size() > 0 && i != nodes.children.size() - 1) { String ss = ""; if (s == "") ss = s + " |"; else ss = s + "| "; dfs(node, ss); } else if (node.children.size() > 0 && i == nodes.children.size() - 1) { String ss = ""; if (s == "") ss = s + " "; else ss = s + " "; dfs(node, ss); } } } public static void main(String [] args) { Scanner sc = new Scanner(System.in); int n = sc.nextInt(); Node [] nodes = new Node[n]; Node root; HashMap<Integer, Node> map = new HashMap<>(); for (int i = 0; i < n; i++) { nodes[i] = new Node(); nodes[i].name = sc.next(); nodes[i].parent = sc.nextInt(); if (i == 0) root = nodes[i]; map.put(i, nodes[i]); } for (int i = 1; i < n; i++) { Node parent = map.get(nodes[i].parent); if (parent != null) parent.children.add(nodes[i]); } for (int i = 0; i < n; i++) { Collections.sort(nodes[i].children,new Comp()); } System.out.println(nodes[0].name); String s = ""; dfs(nodes[0], s); } } class Comp implements Comparator { public int compare(Object s11, Object s22) { Node node1 = (Node) s11; Node node2 = (Node) s22; String s1 = node1.name; String s2 = node2.name; int n1 = s1.length(); int n2 = s2.length(); int min = Math.min(n1, n2); for (int i = 0; i < min; i++) { char c1 = s1.charAt(i); char c2 = s2.charAt(i); if (c1 != c2) { c1 = Character.toUpperCase(c1); c2 = Character.toUpperCase(c2); if (c1 != c2) { c1 = Character.toLowerCase(c1); c2 = Character.toLowerCase(c2); if (c1 != c2) { // No overflow because of numeric promotion return c1 - c2; } } } } return n1 - n2; } } /* 10 my-app -1 src 0 main 1 java 2 resources 2 webapp 2 test 1 java 6 resources 6 pom.xml 0 my-app |-- pom.xml `-- src |-- main | |-- java | |-- resources | `-- webapp `-- test |-- java `-- resources */