1. public class BinaryTreeTest {
    2. //节点类,使用链表的方式实现树;
    3. @Data
    4. public static class Node {
    5. private char data;
    6. private Node left;
    7. private Node right;
    8. public Node(char data, Node left, Node right) {
    9. this.data = data;
    10. this.left = left;
    11. this.right = right;
    12. }
    13. }
    14. public static void main(String[] args) {
    15. //构建一颗二叉树 ABCDEFGHK
    16. Node D = new Node('D', null, null);
    17. Node H = new Node('H', null, null);
    18. Node K = new Node('K', null, null);
    19. Node C = new Node('C', D, null);
    20. Node G = new Node('G', H, K);
    21. Node B = new Node('B', null, C);
    22. Node F = new Node('F', G, null);
    23. Node E = new Node('E', null, F);
    24. Node A = new Node('A', B, E);
    25. //根节点是a,二叉树的三种遍历方式
    26. //前序:根 左 右 ABCDEFGHK
    27. //中序:左 根 右 BDCAEHGKF
    28. //后序:左 右 根 DCBHKGFEA
    29. preErgodic(A);
    30. System.out.println();
    31. midErgodic(A);
    32. System.out.println();
    33. lastErgodic(A);
    34. }
    35. //前序
    36. public static void preErgodic(Node root){
    37. System.out.print(root.getData());
    38. if(root.getLeft() != null){
    39. preErgodic(root.getLeft());
    40. }
    41. if(root.getRight() != null){
    42. preErgodic(root.getRight());
    43. }
    44. }
    45. //中序
    46. public static void midErgodic(Node root){
    47. if(root.getLeft() != null){
    48. midErgodic(root.getLeft());
    49. }
    50. System.out.print(root.getData());
    51. if(root.getRight() != null){
    52. midErgodic(root.getRight());
    53. }
    54. }
    55. //后序
    56. public static void lastErgodic(Node root){
    57. if(root.getLeft() != null){
    58. lastErgodic(root.getLeft());
    59. }
    60. if(root.getRight() != null){
    61. lastErgodic(root.getRight());
    62. }
    63. System.out.print(root.getData());
    64. }
    65. }