关注
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
查看原帖
点赞 3
相关推荐
点赞 评论 收藏
分享
点赞 评论 收藏
分享
牛客热帖
更多
正在热议
更多
# 面试___岗的必刷题单 #
1086次浏览 22人参与
# 应届生被毁约被毁意向了怎么办 #
58747次浏览 293人参与
# 春招开局,你有保底offer吗? #
3970次浏览 42人参与
# 如果不上班,你会去做什么 #
32652次浏览 473人参与
# 哪些公司开暑期实习了? #
2186次浏览 23人参与
# 硬件开发岗知多少 #
23827次浏览 137人参与
# 三月的小目标 #
1543次浏览 42人参与
# 找AI工作应该卷什么? #
774次浏览 19人参与
# 实习生的生存小技巧 #
1142次浏览 34人参与
# 实习生至暗时刻 #
1143次浏览 25人参与
# 小厂一定不能去吗? #
4892次浏览 76人参与
# 你今年的保底offer是哪家 #
170579次浏览 708人参与
# 你经历过哪些AI幻觉? #
810次浏览 21人参与
# 你面试被问到过哪些不会的问题? #
113426次浏览 1904人参与
# AI面试问题分享 #
1891次浏览 44人参与
# 应届生,你找到工作了吗 #
117954次浏览 719人参与
# 职场新人体验 #
171888次浏览 1180人参与
# 26届的你们有几段实习? #
167313次浏览 1081人参与
# 牛友的志愿填报指南 #
54706次浏览 394人参与
# 业务面应该做哪些准备 #
99165次浏览 1110人参与
