public class BinaryTreeTest { //节点类,使用链表的方式实现树; @Data public static class Node { private char data; private Node left; private Node right; public Node(char data, Node left, Node right) { this.data = data; this.left = left; this.right = right; } } public static void main(String[] args) { //构建一颗二叉树 ABCDEFGHK Node D = new Node('D', null, null); Node H = new Node('H', null, null); Node K = new Node('K', null, null); Node C = new Node('C', D, null); Node G = new Node('G', H, K); Node B = new Node('B', null, C); Node F = new Node('F', G, null); Node E = new Node('E', null, F); Node A = new Node('A', B, E); //根节点是a,二叉树的三种遍历方式 //前序:根 左 右 ABCDEFGHK //中序:左 根 右 BDCAEHGKF //后序:左 右 根 DCBHKGFEA preErgodic(A); System.out.println(); midErgodic(A); System.out.println(); lastErgodic(A); } //前序 public static void preErgodic(Node root){ System.out.print(root.getData()); if(root.getLeft() != null){ preErgodic(root.getLeft()); } if(root.getRight() != null){ preErgodic(root.getRight()); } } //中序 public static void midErgodic(Node root){ if(root.getLeft() != null){ midErgodic(root.getLeft()); } System.out.print(root.getData()); if(root.getRight() != null){ midErgodic(root.getRight()); } } //后序 public static void lastErgodic(Node root){ if(root.getLeft() != null){ lastErgodic(root.getLeft()); } if(root.getRight() != null){ lastErgodic(root.getRight()); } System.out.print(root.getData()); }}