关注
//自己重新写了一个Java的,按Ctrl-z可以结束,基本思路是用位图来实现快速发现根节点。然后
//多叉树的存储为链表结构
import java.io.*;
import java.util.*;
class Node {
int val;
Node child;
Node next;
Node(int v) {
val = v;
child = null;
next = null;
}
}
public class Build {
public static void myTraverse(Node root){
Node p = root;
//hierarchy traverse
while(p != null){
//cur root
System.out.print(p.val + " ");
//siblings
while(p.next != null){
System.out.print(p.next.val + " ");
p = p.next;
}
//child
if(p.child != null){
p = p.child;
}
else{
break;
}
}
}
public static void main(String args[]) {
Scanner in = new Scanner(System.in);
//bitmap
//save every node
//find element quickly
Node[] arr = new Node[101];
for (int i = 0; i < 101; i++) {
arr[i] = null;
}
Node coreRoot = null;
int count = 0;
//Ctrl-z end input
while (in.hasNextLine()) {
String line = in.nextLine();
String strs[] = line.split("\\s+");
Node root = null;
for (int i = 0; i < strs.length; i++) {
int num = Integer.valueOf(strs[i]);
//cur root
if (i == 0) {
if (arr[num] == null) {
Node temp = new Node(num);
arr[num] = temp;
}
root = arr[num];
}
//this level siblings
else {
Node temp = null;
if (arr[num] == null) {
temp = new Node(num);
arr[num] = temp;
}
temp = arr[num];
Node p = root;
while (p.next != null) {
p = p.next;
}
p.next = temp;
}
}
//core root
if (count == 0) {
coreRoot = root;
}
count += 1;
}
myTraverse(coreRoot);
}
}
查看原帖
点赞 评论
相关推荐
点赞 评论 收藏
分享
牛客热帖
更多
正在热议
更多
# 春招什么时候投? #
5052次浏览 76人参与
# 春节提前走,你用什么理由请假? #
4917次浏览 107人参与
# 春节前,你还在投简历吗? #
7109次浏览 94人参与
# 实习到现在,你最困惑的一个问题 #
1880次浏览 56人参与
# 牛客AI体验站 #
13323次浏览 253人参与
# 牛友的春节生活 #
1639次浏览 56人参与
# 备战春招/暑实,现在应该做什么? #
1640次浏览 53人参与
# 从夯到拉,锐评职场mentor #
1536次浏览 31人参与
# 聊聊Agent开发 #
14337次浏览 361人参与
# 距离春招还有一个月,你现在是什么开局? #
2906次浏览 53人参与
# 推荐一个值得做的AI项目 #
3902次浏览 125人参与
# 暑期实习什么时候投? #
3538次浏览 84人参与
# 实习想申请秋招offer,能不能argue薪资 #
218549次浏览 1171人参与
# 腾讯工作体验 #
566896次浏览 3700人参与
# 哪些瞬间让你真切感受到了工作的乐趣 #
24440次浏览 105人参与
# 通信硬件2024笔试面试经验 #
269136次浏览 2053人参与
# 实习必须要去大厂吗? #
188488次浏览 1766人参与
# 正在春招的你,也参与了去年秋招吗? #
349896次浏览 2590人参与
# 双非本科的出路是什么? #
208692次浏览 1566人参与
# 最难的技术面是哪家公司? #
65404次浏览 971人参与