Java数据结构和算法(五)二叉排序树(BST)

Java数据结构和算法(五)二叉排序树(BST)

数据结构与算法目录(http://www.javashuo.com/article/p-qvigrlkr-da.html)html

二叉排序树(Binary Sort Tree),又称二叉查找树(Binary Search Tree),亦称二叉搜索树。 二叉排序树的左子树的节点都小于它的父节点,右子树中的节点都大于它的父节点,所以若按按中序遍历则从小到大的排序java

二叉排序树在搜索中的应用很是普遍,同时二叉排序树的一个变种(红黑树)是 java 中 TreeMap 和 TreeSet 的实现基础。node

二叉排序树或者是一棵空树,或者是具备下列性质的二叉树:算法

  1. 若左子树不空,则左子树上全部结点的值均小于它的根结点的值;
  2. 若右子树不空,则右子树上全部结点的值均大于它的根结点的值;
  3. 左、右子树也分别为二叉排序树;
  4. 没有键值相等的节点。

二叉排序树

1、建立二叉排序树

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();
}

2、平衡二叉树

平衡二叉树 (Balanced Binary Tree)又被称为 AVL 树(有别于 AVL 算法),且具备如下性质:它是一 棵空树或它的左右两个子树的高度差的绝对值不超过1,而且左右两个子树都是一棵平衡二叉树。数据结构和算法

之因此有平衡二叉树是由于这个方案很好的解决了二叉查找树退化成链表的问题 ,把插入,查找,删除的时间复杂度最好状况和最坏状况都维持在 O(logN)。可是频繁旋转会使插入和删除牺牲掉 O(logN)左右的时间,不过相对二叉查找树来讲,时间上稳定了不少。测试

平衡二叉树

平衡二叉树的操做详见 http://www.javashuo.com/article/p-djurofdc-o.htmlthis

参考:code

  1. 《二叉排序树》:http://www.javashuo.com/article/p-heajcdrm-b.html
  2. 《Java 中二叉排序树》:http://www.javashuo.com/article/p-sxmszukd-a.html

天天用心记录一点点。内容也许不重要,但习惯很重要!htm

相关文章
相关标签/搜索