更新時(shí)間:2023-03-06 來(lái)源:黑馬程序員 瀏覽量:
Java中的二進(jìn)制搜索樹(shù)(Binary Search Tree,簡(jiǎn)稱(chēng)BST)是一種基于二分查找的數(shù)據(jù)結(jié)構(gòu),其中每個(gè)節(jié)點(diǎn)都包含一個(gè)鍵值和對(duì)應(yīng)的值,同時(shí)滿(mǎn)足以下性質(zhì):
1.左子樹(shù)上所有節(jié)點(diǎn)的鍵值都小于它的根節(jié)點(diǎn)的鍵值。
2.右子樹(shù)上所有節(jié)點(diǎn)的鍵值都大于它的根節(jié)點(diǎn)的鍵值。
3.每個(gè)子樹(shù)都是BST。
以下是Java代碼實(shí)現(xiàn)二進(jìn)制搜索樹(shù)的基本操作(kotlin):
public class BinarySearchTree { private Node root; private class Node { private int key; private Node left, right; public Node(int key) { this.key = key; } } public BinarySearchTree() { root = null; } // 插入操作 public void insert(int key) { root = insert(root, key); } private Node insert(Node x, int key) { if (x == null) return new Node(key); if (key < x.key) x.left = insert(x.left, key); else if (key > x.key) x.right = insert(x.right, key); return x; } // 查找操作 public boolean contains(int key) { return contains(root, key); } private boolean contains(Node x, int key) { if (x == null) return false; if (key == x.key) return true; else if (key < x.key) return contains(x.left, key); else return contains(x.right, key); } // 刪除操作 public void delete(int key) { root = delete(root, key); } private Node delete(Node x, int key) { if (x == null) return null; if (key < x.key) x.left = delete(x.left, key); else if (key > x.key) x.right = delete(x.right, key); else { if (x.right == null) return x.left; if (x.left == null) return x.right; Node t = x; x = min(t.right); x.right = deleteMin(t.right); x.left = t.left; } return x; } private Node deleteMin(Node x) { if (x.left == null) return x.right; x.left = deleteMin(x.left); return x; } private Node min(Node x) { if (x.left == null) return x; return min(x.left); } }
以上是基本的二進(jìn)制搜索樹(shù)操作,包括插入、查找、刪除等。需要注意的是,這里實(shí)現(xiàn)的二進(jìn)制搜索樹(shù)并不是平衡樹(shù),因此在最壞情況下,樹(shù)的高度可能會(huì)達(dá)到 $N$,其中 $N$ 是樹(shù)中節(jié)點(diǎn)的數(shù)量,導(dǎo)致時(shí)間復(fù)雜度退化為 $O(N)$。為了解決這個(gè)問(wèn)題,可以使用平衡二叉樹(shù)(如紅黑樹(shù)、AVL樹(shù)等)來(lái)代替二進(jìn)制搜索樹(shù)。