二叉查找樹的解讀和實現

BST

二叉查找樹是將一組無序的數據構建成一顆有序數據的樹,其設計思想與二分法相似。很好的提升了海量數據查找效率,使得由從頭遍歷到尾的方式轉爲二分查找的方式,時間複雜度從O(n)下降爲O(log(n))。java

概念

  1. 結點:樹上的每一個元素。
  2. 根結點:沒有父結點的結點。
  3. 父結點:結點的上一級結點。
  4. 子結點:結點的下一級結點。
  5. 葉子結點:沒有子結點的結點。
  6. 兄弟結點:擁有同一父結點的相鄰結點。
  7. 結點的度:一個結點中擁有子結點的個數。
  8. 樹的度:樹上最大結點的度。
  9. 結點的層次:以根結點爲1,每深刻一個子結點層次加1。
  10. 樹的高度:樹中最大的結點的層次。

特性

  1. 左子樹全部的結點值均小於,等於根結點值或爲空。
  2. 左子樹全部的結點值均大於,等於根結點值或爲空。
  3. 左、右子樹也分別爲二叉排序樹。
  4. 沒有鍵值相等的結點。

構建

構建二叉查找樹,主要把握幾條原則,小於當前結點的在左邊,大於的在右邊,相等的不予處理。可是狀況下結合實際業務需求,也可在相等時放在左結點或右結點,可是必須統一規則,不能左右都存在相等的。 建立結點對象:node

package com.ytao.bst;

/**
 * Created by YANGTAO on 2019/11/3 0003.
 */
public class Node {

    private Integer value;

    private Node leftChildren;

    private Node rightChildren;

    public Integer getValue() {
        return value;
    }

    public void setValue(Integer value) {
        this.value = value;
    }

    public Node getLeftChildren() {
        return leftChildren;
    }

    public void setLeftChildren(Node leftChildren) {
        this.leftChildren = leftChildren;
    }

    public Node getRightChildren() {
        return rightChildren;
    }

    public void setRightChildren(Node rightChildren) {
        this.rightChildren = rightChildren;
    }

    public Node(Integer value) {
        this.value = value;
    }
}

建立樹的實現:bash

package com.ytao.bst;

/**
 * Created by YANGTAO on 2019/11/3 0003.
 */
public class BuildBST {

    private Node rootNode = null;

    public Node build(int[] vals){
        // 遍歷全部數據,每次都需從根結點開始尋找左或右子節點爲空的位置添加
        for (int val : vals) {
            this.assemble(rootNode, val);
        }

        return rootNode;
    }

    private void assemble(Node node, int val){
        // 建立根結點
        if (node == null){
            rootNode = new Node(val);
        }else{
            // 根據左小右大特性判斷
            if (val < node.getValue()){
                Node leftNode = node.getLeftChildren();
                // 若是左子結點爲空,就添加爲當前結點的左結點,不然繼續遞歸下去
                if (leftNode == null){
                    node.setLeftChildren(new Node(val));
                }else{
                    this.assemble(node.getLeftChildren(), val);
                }
            }else{
                Node rightNode = node.getRightChildren();
                // 若是右子結點爲空,就添加爲當前結點的右結點,不然繼續遞歸下去
                if (rightNode == null){
                    node.setRightChildren(new Node(val));
                }else{
                    this.assemble(rightNode, val);
                }
            }

        }

    }

}

使用[7,5,9,2,11,6]測試是否知足咱們建立樹的要求:測試

public static void main(String[] args) {
    int[] vals = {7,5,9,2,11,6};
    Node node = new BuildBST().build(vals);
    System.out.println(new Gson().toJson(node));
}

測試結果知足咱們要求優化

{
    "value": 7,
    "leftChildren": {
        "value": 5,
        "leftChildren": {
            "value": 2
        },
        "rightChildren": {
            "value": 6
        }
    },
    "rightChildren": {
        "value": 9,
        "rightChildren": {
            "value": 11
        }
    }
}

查找

假設從一百萬個數字中獲取值爲88的數據,若是咱們使用遍歷的方式,最糟的狀況就是排在第一百萬個位置的時候,須要咱們遍歷一百萬次才能獲取到數據,這就是咱們最不想遇到的狀況。這時將一百萬個數據構建成二叉查找樹,咱們就可經過樹快速找到咱們想要的數據。 因爲設定一百萬個數據比較多,這裏咱們舉例當前擁有數據[7,5,9,2,11,6],咱們要找出其中的6。 使用循環遍歷全部數據的方法,咱們須要6次遍歷 7->5->9->2->11->6。 使用二叉查找樹查找時,首先構建好的二叉查找樹的結構如圖:ui

構建二叉查找樹

從根結點開始查找;this

查找根結點

獲取根結點7,不等於6,且6<7,因此繼續找左子結點;設計

查找子結點

獲取到結點5,不等於6,且6>5,因此繼續找右子節點;code

查找子結點

最終獲取到結點6,知足咱們須要的條件。所遍歷的數據爲 7->5->6。 代碼實現查找:對象

package com.ytao.bst;

/**
 * Created by YANGTAO on 2019/11/3 0003.
 */
public class SearchBST {

    public Node search(Node node, int val){
        // 若是結點爲空,說明是沒有了符合的結點
        if (node == null)
            return null;

        int nodeVal = node.getValue();

        // 若是結點上的鍵值相等,就是咱們須要找的結點
        if (val == nodeVal){
            return node;
        }else if (val &lt; nodeVal){ // 若是小於結點的值,那麼必定在結點的左子樹中
            return this.search(node.getLeftChildren(), val);
        }else{
            return this.search(node.getRightChildren(), val);
        }

    }


}

插入

二叉查找樹的插入規則,必須是要插入後的結點是做爲葉子結點。如今向上面的樹中插入10,根據上面所分析到的規則,爲確保二叉查找樹的完整性,最終的插入流程爲7->9->11->10:

插入10的結點

代碼實現:

package com.ytao.bst;

/**
 * Created by YANGTAO on 2019/11/3 0003.
 */
public class InsertBST {

    public void inesrt(Node node, int newVal){
        // 當結點爲空是,說明是做爲根結點
        if (node == null){
            node = new Node(newVal);
        }

        int nodeVal = node.getValue();

        // 若是小於結點的值,插入到左子樹中,大於就插入右子樹中
        if (newVal &lt; nodeVal){
            Node leftNode = node.getLeftChildren();
            // 爲空時,說明爲葉子結點,可插入
            if (leftNode == null){
                node.setLeftChildren(new Node(newVal));
            }else {
                this.inesrt(leftNode, newVal);
            }
        }else if (newVal &gt; nodeVal){
            Node  rightNode = node.getRightChildren();
            if (rightNode == null){
                node.setRightChildren(new Node(newVal));
            }else {
                this.inesrt(rightNode, newVal);
            }
        }else {
            // todo 相等時,可根據具體業務處理,放棄,或在左右樹中選擇一個
        }

    }

}

刪除

刪除結點分爲多種狀況,其中主要分析的:

葉子結點

刪除葉子結點,將所要刪除的葉子結點直接刪除即可,好比刪除結點6。

刪除葉子結點

單子結點的結點

被刪除結點,若是隻有一個子結點,那麼被刪除結點刪除後,該結點的子結點補上其位置,好比刪除結點9。

刪除單子結點的結點

存在左右子結點的結點

爲了更加清楚表達刪除存在左右結點的結點,先向樹中多添加3個結點8,10,15。而後刪除結點9。 這裏的解決方法就是,刪除9後,能夠用前驅結點或後繼結點補上。前驅結點爲左子樹中最大的結點,後繼結點爲右子樹中最小的結點。 如今之後繼結點補上的方案爲:

二叉查找樹

後繼結點補上刪除後的結點:

後繼結點補上示意圖

完成刪除,後繼結點補充上後:

完成刪除後的樹

代碼實現:

package com.ytao.bst;

/**
 * Created by YANGTAO on 2019/11/3 0003.
 */
public class DeleteBST {


    public Node delete(Node node, int delVal) {
        // 爲空時,表明葉子結點
        if (node == null){
            return node;
        }

        int nodeVal = node.getValue();
        Node leftNode = node.getLeftChildren();
        Node rightNode = node.getRightChildren();

        // 刪除的結點,與遍歷到的當前結點作比較,小於,大於或等於
        if (delVal &lt; nodeVal){
            Node tempLeftNode = delete(leftNode, delVal);
            node.setLeftChildren(tempLeftNode);
        } else if(delVal &gt; nodeVal){
            Node tempRightNode = delete(rightNode, delVal);
            node.setRightChildren(tempRightNode);
        } else {
            // 刪除的結點與當前遍歷到的結點相等時
            // 而且左結點爲空時,返回右結點去補上刪除的位置,反則返回左結點補上
            // 說明刪除結點爲單子結點的狀況
            if (leftNode == null){
                return rightNode;
            } else if (rightNode == null){
                return leftNode;
            }

            // 經過查詢最小右結點,獲取後繼結點
            Node minNode = minNode(rightNode);
            int minNodeValue = minNode.getValue();
            node.setValue(minNodeValue);
            // 刪除後繼結點
            Node tempRightNode = delete(rightNode, minNodeValue);
            node.setRightChildren(tempRightNode);
        }
        return node;
    }

    private Node minNode(Node node) {
        // 一直尋找最小值,知道左子節點爲空爲止
        Node leftNode = node.getLeftChildren();
        if (leftNode != null)
            return minNode(leftNode);
        return node;
    }

}

至此上面三中狀況都予知足。

總結

上面對二叉查找樹的操做都已介紹,可是正真使用中,是要結合實際業務進行相關調整來知足本身的需求,否則,一切的優化手段都是假把式。二叉查找樹雖然好用,可是它也是有必定要求,在數據量不大的狀況下,使用遍歷的方式,更加符合咱們的要求,因此它使用場景通常是在海量數據的查詢,用來提查詢效率。

我的博客: https://ytao.top

個人公衆號 ytao

個人公衆號

相關文章
相關標籤/搜索