Java 代码
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
char arr[][] = new char[n][3];
for (int i = 0; i < n; i++) {
String str=sc.next();
char arr1[]=str.toCharArray();
for (int j = 0; j < 3; j++) {
arr[i][j]=arr1[j];
}
}
TreeNode Root = null;
Root = creat(arr, 0, 0);
bianli(Root);
}
// 数据结构
static class TreeNode {
char val;
public TreeNode left;
public TreeNode right;
public TreeNode(char val) {
this.val = val;
}
}
// 创建二叉树
public static TreeNode creat(char arr[][], int i, int j) {
if (i >= arr.length || j >= 3 ||arr[i][j] == '*') {
return null;
}
TreeNode node = new TreeNode(arr[i][j]);
for (int k = 0; k < arr.length; k++) {
if(arr[i][j]==arr[k][0]){
i=k;
break;
}
}
node.left = creat(arr, i, 1);
node.right = creat(arr, i, 2);
return node;
}
//遍历二叉树
public static void bianli(TreeNode node){
if (node==null) return;
System.out.print(node.val);
bianli(node.left);
bianli(node.right);
}
}
下面是失败的尝试
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
char arr[][] = new char[n][3];
for (int i = 0; i < n; i++) {
for (int j = 0; j < 3; j++) {
arr[i][j] = sc.next().charAt(0);
}
}
TreeNode Root = null;
Root = creat(arr, 0, 0);
bianli(Root);
}
// 数据结构
static class TreeNode {
char val;
public TreeNode left;
public TreeNode right;
public TreeNode(char val) {
this.val = val;
}
}
// 创建二叉树
public static TreeNode creat(char arr[][], int i, int j) {
if (i >= arr.length || j >= 3 ||arr[i][j] == '*') {
return null;
}
TreeNode node = new TreeNode(arr[i][j]);
for (int k = 0; k < arr.length; k++) {
if(arr[i][j]==arr[k][0]){
i=k;
break;
}
}
node.left = creat(arr, i, 1);
node.right = creat(arr, i, 2);
return node;
}
//遍历二叉树
public static void bianli(TreeNode node){
if (node==null) return;
System.out.print(node.val);
bianli(node.left);
bianli(node.right);
}
}
紫色报错的原因:输入格式错了,输入的数据之间多加了空格分开。