import java.util.Scanner; class TreeNode{ char val; TreeNode left; TreeNode right; public TreeNode(char val){ this.val = val; } } public class Main { static int i = 0; // 用于遍历字符串 public static void main(String[] args) { Scanner in = new Scanner(System.in); // 注意 hasNext 和 hasNextLine 的区别 while (in.hasNextLine()) { // 注意 while 处理多个 case i = 0; String str = in.nextLine(); // 获取输入的字符串 TreeNode root = createTree(str); inorder(root); } } // 根据先序遍历序列构建二叉树 public static TreeNode createTree(String str){ // 如果遇到“#”则为空 if(str.charAt(i) == '#'){ i++; return null; } // 否则按照val构造树节点 TreeNode root = new TreeNode(str.charAt(i)); i++; // 获取左子树和右子树的根节点 构造出二叉树 root.left = createTree(str); root.right = createTree(str); // 最后将根节点返回 return root; } // 中序遍历 public static void inorder(TreeNode root){ if(root == null){ return; } inorder(root.left); System.out.print(root.val + " "); inorder(root.right); } }