PDD第二题代码,供参考。
import java.util.Scanner;
public class Main {
static class TreeNode {
int father;
int me;
TreeNode firstChild;
TreeNode nextSibling;
String str;
public TreeNode(String str2) {
str = str2;
firstChild = null;
nextSibling = null;
}
}
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int N = in.nextInt();
in.nextLine();
TreeNode[] nodes = new TreeNode[N];
for (int i = 0; i < N; i++) {
String[] str = in.nextLine().split(" ");
nodes[i] = new TreeNode(str[0]);
nodes[i].father = Integer.valueOf(str[1]);
nodes[i].me = i;
}
sort(nodes);
TreeNode tn = nodes[0];
for (int i = 1; i < N; i++) {
TreeNode t = nodes[i];
TreeNode fa = getFather(tn, t.father);
TreeNode child = fa.firstChild;
if (child != null) {
while (child.nextSibling != null)
child = child.nextSibling;
child.nextSibling = t;
} else
fa.firstChild = t;
}
printValues(tn, tn.me, 0);
in.close();
}
public static void printValues(TreeNode root, int cen, int lie) {
if (root == null)
return;
String temp = "";
String temp2 = "";
if (cen != 0) {
for (int i = 0; i < cen - 1; i++) {
if (i == 0) {
temp += " ";
temp2 += " ";
continue;
}
temp += "| ";
temp2 += "| ";
}
temp += "|-- ";
temp2 += "`-- ";
}
if (root.nextSibling != null || lie == 0)
System.out.println(temp + root.str);
else
System.out.println(temp2 + root.str);
printValues(root.firstChild, cen + 1, 0);
if (root.firstChild != null)
printValues(root.firstChild.nextSibling, cen + 1, lie + 1);
}
public static TreeNode getFather(TreeNode root, int n) {
if (root == null || root.me == n)
return root;
TreeNode tn = getFather(root.firstChild, n);
if (tn == null)
tn = getFather(root.nextSibling, n);
return tn;
}
public static void sort(TreeNode[] nodes) {
for (int i = 0; i < nodes.length; i++) {
for (int j = i + 1; j < nodes.length; j++) {
if (nodes[i].father > nodes[j].father) {
TreeNode t = nodes[i];
nodes[i] = nodes[j];
nodes[j] = t;
} else if (nodes[i].father == nodes[j].father) {
if (nodes[i].str.compareTo(nodes[j].str) > 0) {
TreeNode t = nodes[i];
nodes[i] = nodes[j];
nodes[j] = t;
}
}
}
}
}
}
输出如下:
10
my-app -1
src 0
main 1
java 2
resource 2
webapp 2
test 1
java 6
resource 6
pom.xml 0
my-app
|-- pom.xml
`-- src
|-- main
| |-- java
| |-- resource
`-- test
| |-- java
| `-- resource