查找與二叉樹

 

查找與二叉樹

我家園子有幾棵樹系列


 

 

Preface

前面咱們學習了基於線性表的數據結構,如數組,鏈表,隊列,棧等。如今咱們要開始學習一種非線性的數據結構--樹(tree),是否是很興奮呢!讓咱們開始新的系列吧!html

查找

先讓咱們回憶一下線性表的查找,首先最暴力的方法就是作一個線性掃描,一一對比是否是要找的值。這麼作的時間複雜度顯而易見的是 O(N),如表格第一行;更機智一點,咱們採用二分法,首先將線性表排好順序,而後每次對比中間的值就行了,這樣作的時間複雜度就是 O(logN),如表格第二行。但上面的作法都是利用的線性數據結構,而它有致命的缺點;那就是進行動態的操做時,好比插入,刪除;沒法同時實現迅速的查找,只能等從新排序之後再查,效率就低了不少,沒法知足平常需求(以下表)。這個時候咱們的主角就閃亮登場了——二叉查找樹java

圖源node

 

表格
表格

 

二叉查找樹的實現

首先我放幾張圖說明一下什麼是二叉樹,樹的高度,深度等等,詳細的介紹我已經放在這裏,有興趣的話也能夠看看別人的博客。數組

圖源 轉載學習,如侵權則聯繫我刪除!二叉樹數據結構

 

深度
深度

 

廢話很少說咱們開始實現一顆二叉查找樹(BST)吧!
[注] 爲了方便理解大部分代碼都提供了遞歸實現!性能

定義數據結構

public class BST<Key extends Comparable<Key>, Value> {
    private Node root;             // root of BST

    private class Node {
        private Key key;           // sorted by key
        private Value val;         // associated data
        private Node left, right;  // left and right subtrees
        private int size;          // number of nodes in subtree

        public Node(Key key, Value val, int size) {
            this.key = key;
            this.val = val;
            this.size = size;
        }
    }

    /** * Initializes an empty symbol table. */
    public BST() {}
    /** * Returns the number of key-value pairs in this symbol table. * @return the number of key-value pairs in this symbol table */
    public int size() {
        return size(root);
    }

    // return number of key-value pairs in BST rooted at x
    private int size(Node x) {
        if (x == null) return 0;
        else return x.size;
    }

}

中序遍歷

咱們知道二叉查找樹的任一個節點,他的左子結點比他小,右子節點比他大,哈,那麼咱們只要進行一波中序遍歷就能夠完成數據的排序啦!學習

/*************************************************************************** * 中序遍歷,非遞歸版本 ***************************************************************************/
    public Iterable<Key> keys() {
        Stack<Node> stack = new Stack<Node>();
        Queue<Key> queue = new Queue<Key>();
        Node x = root;
        while (x != null || !stack.isEmpty()) {
            if (x != null) {
                stack.push(x);
                x = x.left;
            } else {
                x = stack.pop();
                queue.enqueue(x.key);
                x = x.right;
            }
        }
        return queue;
    }
    /************************************************************************ * 中序遍歷,遞歸打印 ************************************************************************/
    public void inOrder(Node* root) {
 		if (root == null) return;
  		inOrder(root.left);
  		print root // 此處爲僞代碼,表示打印 root 節點
  		inOrder(root.right);
}

查找操做

/************************************************************************ * 非遞歸 ************************************************************************/
    Value get(Key key){
        Node x = root;
        while(x != null){
            int cmp =  key.compareTo(x.key);
            if(cmp<0)
                x = x.left;
            else if(cmp>0) 
                x = x.right;
            else return 
                x.value;
        }
        return null;
    }
    /************************************************************************ * 遞歸 ************************************************************************/
    public Value get(Key key) {
        return get(root, key);
    }

    private Value get(Node x, Key key) {
        if (x == null) return null;
        int cmp = key.compareTo(x.key);
        if      (cmp < 0) return get(x.left, key);
        else if (cmp > 0) return get(x.right, key);
        else              return x.val;
    }

插入

/************************************************************************ * 非遞歸 ************************************************************************/
public void put(Key key, Value val) {
        Node z = new Node(key, val);
        if (root == null) {
            root = z;
            return;
        }

        Node parent = null, x = root;
        while (x != null) {
            parent = x;
            int cmp = key.compareTo(x.key);
            if (cmp < 0)
                x = x.left;
            else if (cmp > 0)
                x = x.right;
            else {
                x.val = val;
                return;
            }
        }
        int cmp = key.compareTo(parent.key);
        if (cmp < 0)
            parent.left = z;
        else
            parent.right = z;
    }
/************************************************************************ * 遞歸版本 ************************************************************************/
public void put(Key key, Value value) {
        root = put(root, key, value);
    }

    private Node put(Node x, Key key, Value value) {
        if (x == null)
            return new Node(key, value, 1);
        int cmp = key.compareTo(x.key);
        if (cmp < 0)
            x.left = put(x.left, key, value);
        else if (cmp > 0)
            x.right = put(x.right, key, value);
        else
            x.value = value;
        x.size = 1 + size(x.left) + size(x.right);
        return x;
    }

刪除

刪除有兩種方式,一種是合併刪除,另外一種是複製刪除,這裏我主要講第二種,想了解第一種能夠點這裏ui

刪除最小值

在正式的刪除以前讓咱們先熱身一下,看看怎麼刪除一棵樹的最小值(如圖)。this

步驟spa

  • 咱們先找到最小值,即不斷查找節點的左子節點,若無左節點,那他就是最小值。
  • 找到最小的節點後,返回他的右子節點給上一層,最小節點會被GC機制回收
  • 由於用的是遞歸方法,因此依次更新節點數量

 


 

 

public void deleteMin(){
    root = deleteMin(root);
}

private Node deleteMin(Node x){
    if (x.left == null) return x.right;
    x.left = deleteMin(x.left);
    x.N = size(x.left) + size(x.right) + 1;
    return x;
}

複製(拷貝)刪除

在說複製刪除以前,咱們須要先熟悉二叉查找樹的前驅和後繼(根據中序遍歷衍生出來的概念)。

  • 前驅:A節點的前驅是其左子樹中最右側節點。
  • 後繼:A節點的後繼是其右子樹中最左側節點。

 

BSTcopyDelete
BSTcopyDelete

 

上圖是複製刪除的原理,咱們既能夠用前驅節點 14 代替,又能夠用後繼節點 18 代替。

步驟

 

BSTcDelete
BSTcDelete

 

如圖所示,咱們分爲四個步驟

  1. 將指向即將被刪除的節點的連接保存爲t;
  2. 將 x 指向它的後繼節點 min(t.right);
  3. 將 x 的右連接(本來指向一顆全部節點都大於 x.key 的二叉查找樹) 指向deleteMin(t.right),也就是在刪除後全部節點仍然都大於 x.key 的子二叉查找樹。
  4. 將 x 的左連接(本爲空) 設爲 t.left
public void delete(Key key){
    root = delete(root,key);
}
private Node min(Node x){
    if(x.left == null) return x;
    else return min(x.left);
}
private Node delete(Node x, Key key){
    if(x==null) return null;
    int cmp = key.compareTo(x.key);
    if(cmp < 0) x.left = delete(x.left, key);
    else if(cmp > 0) 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;
    }
    x.N = size(x.left) + size(x.right) + 1;
    return x;
}

在前面的代碼中,咱們老是刪除node中的後繼結點,這樣必然會下降右子樹的高度,在前面中咱們知道,咱們也可使用前驅結點來代替被刪除的結點。因此咱們能夠交替的使用前驅和後繼來代替被刪除的結點。

J.Culberson從理論證明了使用非對稱刪除, IPL(內部路徑長度)的指望值是 O(n√n), 平均查找時間爲 O(√n),而使用對稱刪除, IPL的指望值爲 O(nlgn),平均查找時間爲 O(lgn)。

Rank

查找節點 x 的排名

public int rank(Key key){
    return rank(key, root);
}

private int rank(Key key, Node x){
    // 返回以 x 爲根節點的子樹中小於x.key的數量
    if(x == null) return 0;
    int cmp = key.compareTo(x.key);
    if(cmp<0) return rank(key,x.left);
    else if(cmp>0) return 1 + size(x.left) + rank(key,x.right);
    else return size(x.left);
}

2-3查找樹

經過前面的分析咱們知道,通常狀況下二叉查找樹的查找,插入,刪除都是 O(lgn)的時間複雜度,可是二叉查找樹的時間複雜度是和樹的高度是密切相關的,若是咱們以升序的元素進行二叉樹的插入,咱們會發現,此時的二叉樹已經退化成鏈表了,查找的時間複雜度變成了 O(n),這在性能上是不可容忍的退化!那麼咱們該怎麼解決這個問題呢?

答案相信你們都知道了,那就是構建一顆始終平衡的二叉查找樹。那麼有哪些平衡二叉查找樹呢?如何實現?

這些咱們留到下節再講。

總結

這一節咱們學會了使用非線性的數據結構--二叉查找樹來高效的實現查找,插入,刪除操做。分析了它的性能,在隨機插入的狀況下,二叉查找樹的高度趨近於 2.99lgN ,平均查找時間複雜度爲 1.39lgN(2lnN),並且在升序插入的狀況下,樹會退化成鏈表。這些知識爲咱們後面學習2-3查找樹和紅黑樹打下了基礎。

相關文章
相關標籤/搜索