版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/BLueberry_Pie/article/details/84654192
数据结构实验之二叉树五:层序遍历
Time Limit: 1000 ms Memory Limit: 65536 KiB
Problem Description
已知一个按先序输入的字符序列,如abd,,eg,,,cf,,,(其中,表示空结点)。请建立二叉树并求二叉树的层次遍历序列。
Input
输入数据有多行,第一行是一个整数t (t<1000),代表有t行测试数据。每行是一个长度小于50个字符的字符串。
Output
输出二叉树的层次遍历序列。
Sample Input
2
abd,,eg,,,cf,,,
xnl,,i,,u,,
Sample Output
abcdefg
xnuli
Hint
Source
xam
import java.io.*;
import java.util.*;
class Main {
public static void main(String[] args) throws IOException {
sc.in(System.in);
// while (!sc.to.hasMoreTokens()) {
int t = sc.nextInt();
while (t-- > 0) {
BT<Character> bt = new BT<>();
LinkedList<Character> Tree = new LinkedList<>();
String s = sc.next();
char[] c = s.toCharArray();
for (int i = 0; i < c.length; i++) {
if (c[i] == ',')
Tree.add(null);
else
Tree.add(c[i]);
}
TN<Character> root = bt.CBP(Tree);
bt.LevelOrder(root);
System.out.println();
}
}
}
class BT<T> {
public TN<T> CBP(LinkedList<T> data) {
TN<T> root = null;
T d = data.removeFirst();
if (d != null) {
root = new TN<T>(d, null, null);
root.l = CBP(data);
root.r = CBP(data);
}
return root;
}
public void PreOrder(TN<T> root) {
if (root != null) {
System.out.print(root.d);
PreOrder(root.l);
PreOrder(root.r);
}
}
public void InOrder(TN<T> root) {
if (root != null) {
InOrder(root.l);
System.out.print(root.d);
InOrder(root.r);
}
}
public void PostOrder(TN<T> root) {
if (root != null) {
PostOrder(root.l);
PostOrder(root.r);
System.out.print(root.d);
}
}
public void LevelOrder(TN<T> root) {
if(root==null) return;
LinkedList<TN> queue = new LinkedList<>();
TN<T> p;
queue.add(root);
while (!queue.isEmpty()) {
p = queue.removeFirst();
System.out.print(p.d);
if (p.l != null) {
queue.add(p.l);
}
if (p.r != null) {
queue.add(p.r);
}
}
}
}
class TN<T> {
public T d;
public TN<T> l;
public TN<T> r;
public TN(T d, TN<T> l, TN<T> r) {
this.d = d;
this.l = l;
this.r = r;
}
}
class sc {
static BufferedReader re;
static StringTokenizer to;
static void in(InputStream in) {
re = new BufferedReader(new InputStreamReader(in), 32678);
to = new StringTokenizer("");
}
static String next() throws IOException {
while (!to.hasMoreTokens()) {
to = new StringTokenizer(re.readLine());
}
return to.nextToken();
}
static int nextInt() throws IOException {
return Integer.parseInt(next());
}
static double nextDouble() throws IOException {
return Double.parseDouble(next());
}
}