public class TreeNode{ public E e; public TreeNode left; public TreeNode right; public TreeNode(E e) { this.e = e; } } public class Main { public static void main(String[] args) { TreeNode root = new TreeNode<>("A"); root.left = new TreeNode<>("B"); root.right = new TreeNode<>("E"); root.left.left = new TreeNode<>("C"); root.left.right = new TreeNode<>("D"); root.right.left = new TreeNode<>("F"); root.right.right = new TreeNode<>("G"); front(root); System.out.println(); middle(root); System.out.println(); rear(root); } // 部分子树也满足该规律 // 到达结点就输出,先左后右 // A B C D E F G private static void front(TreeNode root) { if (root == null) return; System.out.print(root.e + " "); front(root.left); front(root.right); } // 先输出左子树结点,再输出当前结点,最后右子树 // C B D A F E G private static void middle(TreeNode root) { if (root == null) return; middle(root.left); System.out.print(root.e + " "); middle(root.right); } // 先遍历左子树,再遍历右子树,最后输出结点本身 // C D B F G E A private static void rear(TreeNode root) { if (root == null) return; rear(root.left); rear(root.right); System.out.print(root.e + " "); } }



