import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.List; import java.util.stream.Collectors; /** * @描述:遍历二叉树 * @思路: * @复杂度: * @链接: https://www.nowcoder.com/practice/566f7f9d68c24691aa5abd8abefa798c */ class TraversalBinaryTree { public static void preOrderTraversal(TreeNode root) { if(root==null) { return; } System.out.print(root.value + " "); if (root.left != null) { preOrderTraversal(root.left); } if (root.right != null) { preOrderTraversal(root.right); } } public static void inOrderTraversal(TreeNode root) { if (root.left != null) { inOrderTraversal(root.left); } System.out.print(root.value + " "); if (root.right != null) { inOrderTraversal(root.right); } } public static void postOrderTraversal(TreeNode root) { if(root==null) { return; } if (root.left != null) { postOrderTraversal(root.left); } if (root.right != null) { postOrderTraversal(root.right); } System.out.print(root.value + " "); } } public class Main { public static void main(String[] args) throws Exception { BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); String[] firstRow = in.readLine().split(" "); int row = Integer.parseInt(firstRow[0]); String[] nodeValueArr = new String[row * 3]; TreeNode root = TreeUtils.makeBinaryTreeByInput(in); // System.out.println("先序遍历:"); TraversalBinaryTree.preOrderTraversal(root); // System.out.println("\n" + "中序遍历:"); System.out.println(); TraversalBinaryTree.inOrderTraversal(root); // System.out.println("\n" + "后序遍历:"); System.out.println(); TraversalBinaryTree.postOrderTraversal(root); } } class TreeUtils { private static TreeNode root; /** * 采用递归的方式创建一颗二叉树 * n 行每行三个整数 fa,lch,rch, * 表示 fa 的左儿子为 lch,右儿子为 rch。(如果 lch 为 0 则表示 fa 没有左儿子,rch同理) * 构造后是二叉树的二叉链表表示法 */ //创建一个树的结点 public static TreeNode<String> makeBinaryTreeByInput(BufferedReader in) throws Exception{ String[] nodeVals = in.readLine().split(" "); //数组中第一个数是根节点 TreeNode<String> node = new TreeNode<>(nodeVals[0]); //通过递归确定了层数 if (!"0".equals(nodeVals[1])) { node.left = makeBinaryTreeByInput(in); } if (!"0".equals(nodeVals[2])) { node.right = makeBinaryTreeByInput(in); } return node; } } class TreeNode<T> { public T value; public TreeNode<T> left; public TreeNode<T> right; public TreeNode(T value) { this.value = value; } public TreeNode( ) { } public TreeNode(TreeNode left, T value, TreeNode right) { this.value = value; this.left = left; this.right = right; } }