image.png

    1. package com.atguigu.binarysorttree;
    2. /**
    3. * 二叉排序树
    4. *
    5. * @author Dxkstart
    6. * @create 2022-04-10-15:48
    7. */
    8. public class BinarySortTreeDemo {
    9. public static void main(String[] args) {
    10. int[] arr = new int[]{7,3,10,12,5,1,9};
    11. BinarySortTree binarySortTree = new BinarySortTree();
    12. // 向树中添加
    13. for (int i = 0; i < arr.length; i++) {
    14. binarySortTree.add(new Node(arr[i]));
    15. }
    16. // 遍历
    17. binarySortTree.infixOrder();
    18. }
    19. }
    20. // 创建二叉排序树
    21. class BinarySortTree {
    22. private Node root;
    23. // 添加节点的方法
    24. public void add(Node node) {
    25. // 如果是空树
    26. if (root == null) {
    27. root = node;
    28. } else {
    29. root.add(node);
    30. }
    31. }
    32. // 中序遍历
    33. public void infixOrder() {
    34. if (root != null) {
    35. root.infixOrder();
    36. }else {
    37. System.out.println("此二叉排序树为空");
    38. }
    39. }
    40. }
    41. class Node {
    42. int value;
    43. Node left;
    44. Node right;
    45. public Node(int value) {
    46. this.value = value;
    47. }
    48. // 添加节点的方法
    49. public void add(Node node) {
    50. if (node == null) {
    51. return;
    52. }
    53. // 判断传入的节点的值,和当前子树的根节点的值的关系
    54. if (node.value < this.value) {
    55. // 如果当前节点的左节点为空
    56. if (this.left == null) {
    57. // 直接将该节点挂在this节点的左边
    58. this.left = node;
    59. return;
    60. } else {
    61. // 继续向左递归
    62. this.left.add(node);
    63. }
    64. // 当前节点大于this节点的值
    65. } else if (node.value > this.value) {
    66. // 如果this节点的右节点为空
    67. if (this.right == null) {
    68. // 直接将该节点挂在this节点的右边
    69. this.right = node;
    70. return;
    71. } else {
    72. //继续向右递归
    73. this.right.add(node);
    74. }
    75. }
    76. }
    77. // 中序遍历
    78. public void infixOrder() {
    79. if (this.left != null) {
    80. // 向左递归
    81. this.left.infixOrder();
    82. }
    83. // 中间节点
    84. System.out.println(this.value);
    85. if (this.right != null) {
    86. // 向右递归
    87. this.right.infixOrder();
    88. }
    89. }
    90. @Override
    91. public String toString() {
    92. return "Node{" +
    93. "value=" + value +
    94. '}';
    95. }
    96. }

    image.png