首页 > 技术文章 > 如何构建二叉排序树

pengsay 2021-03-28 09:18 原文

什么是二叉排序树?

二叉排序树(Binary Sort Tree),又称二叉查找树(Binary Search Tree),亦称二叉搜索树。是数据结构中的一类。在一般情况下,查询效率比链表结构要高。

 

 

 

 在算法设计中,往往需要有检索查找数据的操作,如果在数据量比较庞大的情况下用一般的数组或者链表之类的线性数据结构去实现的话,那么时间上会吃不消,这时我们就可以利用在大学时候学过的一门课叫数据结构与算法,其中就有一个数据结构——二叉排序树,它的查找能力是比较快的,平均时间复杂度一般是O(logn),好了废话不多说,直接上代码:

 1 /**
 2  * 二叉排序树
 3  */
 4 public class BinarySortTreeUtil {
 5 
 6     public static void add(Node root, int data) {
 7        if (!find(root, data)) {
 8            addNode(root, data);
 9        }
10     }
11 
12     /**
13      * 添加元素
14      * 如果要添加的元素跟二叉树中的某一个元素相等则不添加
15      * @param root
16      * @param data
17      */
18     private static void addNode(Node root, int data) {
19         if (data < root.data) {
20             if (root.left == null) {
21                 // 如果左孩子为空,则直接赋值给左孩子
22                 root.left = new Node(data, null, null);
23             } else {
24                 // 左孩子
25                 addNode(root.left, data);
26             }
27         } else if (data > root.data){
28             if (root.right == null) {
29                 // 如果右孩子为空,则直接赋值给右孩子
30                 root.right = new Node(data, null, null);
31             } else {
32                 // 右孩子
33                 addNode(root.right, data);
34             }
35         }
36     }
37 
38     /**
39      * 二分查找
40      * @param data
41      * @return
42      */
43     public static boolean find(Node root, int data) {
44         if (root == null) {
45             return false;
46         }
47         if (data == root.data) {
48             return true;
49         } else if (data < root.data) {
50             return find(root.left, data);
51         } else {
52             return find(root.right, data);
53         }
54     }
55 }
56 
57 class Node {
58     int data;
59     Node left;
60     Node right;
61 
62     public Node(int data, Node left, Node right) {
63         this.data = data;
64         this.left = left;
65         this.right = right;
66     }
67 }

 

推荐阅读