题解 | 二叉树遍历
二叉树遍历
https://www.nowcoder.com/practice/4b91205483694f449f94c179883c1fef
import java.util.Scanner; // 注意类名必须为 Main, 不要有任何 package xxx 信息 public class Main { static class BTNode { public char val; public BTNode left; public BTNode right; public BTNode(char val){ this.val=val; } } public int i = 0; public BTNode create(String str) { if(str.charAt(i)=='#'||i>=str.length()){ i++; return null; } BTNode root = new BTNode(str.charAt(i)); i++; root.left = create(str); root.right = create(str); return root; } public void inOrder(BTNode root) { if (root == null) { return; } inOrder(root.left); System.out.print(root.val + " "); inOrder(root.right); } public static void main(String[] args) { Scanner in = new Scanner(System.in); // 注意 hasNext 和 hasNextLine 的区别 while (in.hasNextLine()) { // 注意 while 处理多个 case String str = in.nextLine(); Main ma = new Main(); BTNode root = ma.create(str); ma.inOrder(root); } } }