算法其實很簡單—二叉排序樹的構建

目錄

 

1.什麼是二叉排序樹

2.構建二叉排序樹的思路

3.代碼實現

4.待辦


1.什麼是二叉排序樹

二叉排序樹(Binary Sort Tree),又稱二叉查找樹(Binary Search Tree),亦稱二叉搜索樹。是數據結構中的一類。在一般情況下,查詢效率比鏈表結構要高。

二叉排序樹特點:

(1)若左子樹不空,則左子樹上所有結點的值均小於它的根結點的值;

(2)若右子樹不空,則右子樹上所有結點的值均大於它的根結點的值;

(3)左、右子樹也分別爲二叉排序樹;

(4)沒有鍵值相等的結點。

簡單說,就是每個父節點大於當前節點的左子節點,小於當前節點的右子節點。

2.構建二叉排序樹的思路

以下講解將一個數組轉爲二叉排序樹的思路:

  1. 添加子節點的時候,如果二叉樹的root節點爲null,則該節點爲root節點
  2. 如果root節點不爲null,進行以下步驟
  3. 如果子節點(即新增節點)的值小於該節點(第一次爲root節點,後續爲當前節點),分兩種情況:          

          3.1 如果該節點的左子節點爲null,則將新增節點做爲當前節點的左子節點           

          3.2 如果該節點的左子節點不爲null,則將當前節點的左子節點作爲父節點,重複 2-3-4步驟

    4. 如果子節點的值不小於該節點的值,分兩種情況:

           4.1、如果該節點的右子節點爲null,則將新增節點作爲當前節點的右子節點

          4.2、如果該節點的右子節點不爲null,則將當前節點的右子節點作爲父節點,重複 2-3-4步驟

具體實現可參考以下代碼

3.代碼實現

/**
 * @author 浪子傑
 * @version 1.0
 * @date 2020/5/31
 */
public class BinarySearchTreeDemo {

    public static void main(String[] args) {
        BinarySearchTree binarySearchTree = new BinarySearchTree();
        int[] arr = {7, 3, 10, 12, 5, 1, 9};
        for (int i : arr) {
            Node node = new Node(i);
            binarySearchTree.add(node);
        }
        binarySearchTree.infixOrder();
    }
}

class BinarySearchTree {

    private Node root;

    /**
     * 添加子節點
     *
     * @param node
     */
    public void add(Node node) {
        if (root == null) {
            root = node;
        } else {
            root.add(node);
        }
    }

    /**
     * 中序遍歷
     */
    public void infixOrder() {
        if (root != null) {
            root.middleOrder();
        } else {
            System.out.println("當前root爲空");
        }
    }
}

class Node {

    private int value;
    private Node left;
    private Node right;

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

    /**
     * 添加節點
     *
     * @param node
     */
    public void add(Node node) {
        // 如果該節點爲null,直接返回
        if (node == null) {
            return;
        }
        // add的節點小於當前節點,說明應該在當前節點的左邊
        // 否則放在當前節點的右邊
        if (node.value < this.value) {
            // 如果當前節點的左邊沒有子節點,則直接把add節點放在當前節點的左子節點
            // 否則的話,遍歷當前左子節點,直到找到合適位置
            if (this.left == null) {
                this.left = node;
            } else {
                this.left.add(node);
            }
        } else {
            if (this.right == null) {
                this.right = node;
            } else {
                this.right.add(node);
            }
        }
    }

    /**
     * 中序遍歷
     */
    public void middleOrder() {
        if (this.left != null) {
            this.left.middleOrder();
        }
        System.out.println(this);
        if (this.right != null) {
            this.right.middleOrder();
        }
    }

    @Override
    public String toString() {
        return "Node{" +
                "value=" + value +
                '}';
    }
}

4.待辦

1、二叉排序樹的節點刪除

2、二叉排序樹的優化,即平衡二叉樹

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章