數據結構與算法目錄(http://www.javashuo.com/article/p-qvigrlkr-da.html)html
二叉排序樹(Binary Sort Tree),又稱二叉查找樹(Binary Search Tree),亦稱二叉搜索樹。 二叉排序樹的左子樹的節點都小於它的父節點,右子樹中的節點都大於它的父節點,所以若按按中序遍歷則從小到大的排序java
二叉排序樹在搜索中的應用很是普遍,同時二叉排序樹的一個變種(紅黑樹)是 java 中 TreeMap 和 TreeSet 的實現基礎。node
二叉排序樹或者是一棵空樹,或者是具備下列性質的二叉樹:算法
public class BinarySortTree<T extends Comparable<T>> { private Node<T> root; public void add(Node<T> node) { if (root == null) { root = node; } else { root.add(node); } } public void midOrder() { root.midOrder(); } public static class Node<E extends Comparable<E>> { private E element; private Node<E> left; private Node<E> right; public Node(E element) { this.element = element; } public Node(E element, Node<E> left, Node<E> right) { this.element = element; this.left = left; this.right = right; } // 遞歸添加節點 public void add(Node<E> node) { if (node.element.compareTo(this.element) < 0) { 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 midOrder() { if (this.left != null) { this.left.midOrder(); } System.out.printf("%s ", this.element); if (this.right != null) { this.right.midOrder(); } } } }
測試:數據結構
public void test() { Integer[] arr = {3, 2, 7, 6, 1}; BinarySortTree<Integer> bst = new BinarySortTree<>(); for (Integer i : arr) { bst.add(new BinarySortTree.Node(i)); } // 1, 2, 3, 6, 7 bst.midOrder(); }
平衡二叉樹 (Balanced Binary Tree)又被稱爲 AVL 樹(有別於 AVL 算法),且具備如下性質:它是一 棵空樹或它的左右兩個子樹的高度差的絕對值不超過1,而且左右兩個子樹都是一棵平衡二叉樹。數據結構和算法
之因此有平衡二叉樹是由於這個方案很好的解決了二叉查找樹退化成鏈表的問題 ,把插入,查找,刪除的時間複雜度最好狀況和最壞狀況都維持在 O(logN)。可是頻繁旋轉會使插入和刪除犧牲掉 O(logN)左右的時間,不過相對二叉查找樹來講,時間上穩定了不少。測試
平衡二叉樹的操做詳見 http://www.javashuo.com/article/p-djurofdc-o.htmlthis
參考:code
天天用心記錄一點點。內容也許不重要,但習慣很重要!htm