什么是二叉排序樹?
二叉排序樹(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 }