题解 | #二叉树遍历#
二叉树遍历
https://www.nowcoder.com/practice/4b91205483694f449f94c179883c1fef
import java.util.Scanner; // 注意类名必须为 Main, 不要有任何 package xxx 信息 class TreeNode { public char val; public TreeNode leftChild; public TreeNode rightChild; public TreeNode(char val) { this.val = val; } } public class Main { public static int i = 0; public static TreeNode createTree(String s){ TreeNode root = null; //1.遍历字符串s if(s.charAt(i) != '#'){ //2.根据前序遍历创建二叉树 root = new TreeNode(s.charAt(i)); i++; root.leftChild = createTree(s); root.rightChild = createTree(s); }else{ i++; } //3.返回根节点 return root; } public static void inOrder(TreeNode root){ if(root == null){ return; } inOrder(root.leftChild); System.out.print(root.val+" "); inOrder(root.rightChild); } public static void main(String[] args) { Scanner in = new Scanner(System.in); // 注意 hasNext 和 hasNextLine 的区别 while (in.hasNextLine()) { String str = in.nextLine(); TreeNode root = createTree(str); inOrder(root); } } }