题解 | #二叉树遍历#
二叉树遍历
https://www.nowcoder.com/practice/4b91205483694f449f94c179883c1fef
import java.util.Scanner; class TreeNode { public char val; TreeNode left; TreeNode right; TreeNode() { } TreeNode(char val) { this.val = val; } } //二叉树的构建及遍历 public class Main { public static void main(String[] args) { Scanner in = new Scanner(System.in); while (in.hasNextLine()) { String str = in.nextLine(); TreeNode root = creatTree(str); inorder(root); } } public static int i = 0; public static TreeNode creatTree(String str) { TreeNode root = null; if (str.charAt(i) != '#') { root = new TreeNode(str.charAt(i)); i++; root.left = creatTree(str); root.right = creatTree(str); } else { i++; } return root; } public static void inorder(TreeNode root) { if (root == null) { return; } inorder(root.left); System.out.print(root.val + " "); inorder(root.right); } }