二叉搜索树又称二叉查找树,二叉排序树,它具有以下几点特点:

    • 如果它的左子树不为空,则左子树上结点的值都小于根结点的值;
    • 如果它的右子树不为空,则右子树上结点的值都大于根结点的值;
    • 子树也同样遵循以上两点。

    下面来实现一颗二叉搜索树

    1. /**
    2. * 二叉查找树
    3. * @author xzf
    4. * @date 2021/1/20 14:12
    5. */
    6. public class SearchTree {
    7. private int data;
    8. SearchTree left;
    9. SearchTree right;
    10. public SearchTree(int data) {
    11. this.data = data;
    12. this.left = null;
    13. this.right = null;
    14. }
    15. /**
    16. * 插入元素
    17. * @param root
    18. * @param data
    19. */
    20. public void insert(SearchTree root,int data){
    21. if(root.data<data){
    22. if(root.right == null){
    23. // 根结点下没有子结点
    24. root.right = new SearchTree(data);
    25. }else {
    26. insert(root.right,data);
    27. }
    28. }else {
    29. if (root.left == null) {
    30. root.left = new SearchTree(data);
    31. }else {
    32. insert(root.left,data);
    33. }
    34. }
    35. }
    36. /**
    37. * 中序输出
    38. * @param root
    39. */
    40. public void in(SearchTree root){
    41. if(root != null) {
    42. in(root.left);
    43. System.out.print(root.data + " ");
    44. in(root.right);
    45. }
    46. }
    47. /**
    48. * 查找某个元素
    49. * @param root
    50. * @param data
    51. */
    52. public SearchTree find(SearchTree root,int data){
    53. SearchTree node = root;
    54. while (node.data != data){
    55. if(node.data<data){
    56. node = node.right;
    57. }else {
    58. node = node.left;
    59. }
    60. if(node == null){
    61. return null;
    62. }
    63. }
    64. return node;
    65. }
    66. public static void main(String[] args) {
    67. //快速排序,归并排序,二叉树排序
    68. int data[] = {0,5,9,1,2,3,10};
    69. //第一个点作为跟结点
    70. SearchTree root = new SearchTree(data[0]);
    71. for(int i = 1 ; i < data.length ; i ++) {
    72. root.insert(root, data[i]);
    73. }
    74. System.out.println("中序遍历:");
    75. root.in(root);
    76. System.out.println(root.find(root,7));
    77. }
    78. }