题解 | 二叉树遍历
二叉树遍历
https://www.nowcoder.com/practice/4b91205483694f449f94c179883c1fef
import java.util.Scanner; class TreeNode{ char val; TreeNode left; TreeNode right; public TreeNode(char val){ this.val=val; } } public class Main { public static void show(TreeNode root){ if(root==null){ return; } show(root.left); System.out.print(root.val+" "); show(root.right); } public static void main(String[] args) { Scanner in = new Scanner(System.in); // 注意 hasNext 和 hasNextLine 的区别 while (in.hasNext()) { // 注意 while 处理多个 case TreeNode root=null; String str=in.nextLine(); char[]ch=str.toCharArray(); root=create(ch); show(root); } } public static int i=0; public static TreeNode create(char[] ch){ TreeNode root=null; if(ch[i]!='#'){ root=new TreeNode(ch[i]); i++; root.left=create(ch); root.right=create(ch); }else{ i++; } return root; } }