关注
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
相关推荐
牛客热帖
更多
正在热议
更多
# 为了入行xx岗,我学了__ #
4782次浏览 89人参与
# 小厂实习有必要去吗 #
77813次浏览 368人参与
# 实习的你做了哪些离谱的工作 #
7491次浏览 109人参与
# Prompt分享 #
1546次浏览 53人参与
# 简历第一个项目做什么 #
5993次浏览 93人参与
# 你都见过什么样的草台班子? #
3369次浏览 41人参与
# 被说“做题家”,你的反应是_____? #
1187次浏览 48人参与
# 如果让你发明个APP,你会想做什么 #
1568次浏览 48人参与
# 听到哪句话代表面试稳了OR挂了? #
124530次浏览 559人参与
# 工作压力大,你会干什么? #
11042次浏览 269人参与
# 找实习记录 #
22768次浏览 406人参与
# 大家实习每天都在干啥 #
112185次浏览 606人参与
# 如果不上班,你会去做什么 #
5449次浏览 229人参与
# 邪修省钱套路 #
6293次浏览 218人参与
# AI让你的思考变深了还是变浅了? #
3690次浏览 107人参与
# 金三银四,你有感觉到吗 #
673360次浏览 6040人参与
# 分享一个让你热爱工作的瞬间 #
57129次浏览 482人参与
# 你想跟着什么样领导? #
45462次浏览 231人参与
# 我的求职精神状态 #
419364次浏览 3071人参与
# 通信硬件薪资爆料 #
1200319次浏览 7192人参与
顺丰集团工作强度 406人发布
