All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.neko233.toolchain.common.algorithm.bst.BinarySearchTree Maven / Gradle / Ivy

package com.neko233.toolchain.common.algorithm.bst;


import java.util.Comparator;

@SuppressWarnings("unchecked")
public class BinarySearchTree implements BstApi {

    private Comparator comparator;

    private BstNode root;
    private int size;

    public BinarySearchTree() {
    }

    public BinarySearchTree(Comparator comparator) {
        this.comparator = comparator;
    }

    public int getSize() {
        return size;
    }

    /**
     * BST Insert
     *
     * @param element 元素
     */
    public void addNode(T element) {
        if (element == null) {
            throw new IllegalArgumentException("element must be not null");
        }

        // init
        if (root == null) {
            root = new BstNode(element, null);
            size++;
            return;
        }

        // add element and maintain BST
        BstNode parent = root;
        BstNode point = root;
        // BST core
        int cmp = 0;

        // recursive choose exists parent for new element
        while (point != null) {
            // 大小
            cmp = compare(element, point.element);
            parent = point;
            if (cmp > 0) {
                point = point.right;
            } else if (cmp < 0) {
                point = point.left;
            } else {
                // exit
                point.element = element;
                return;
            }
        }

        // if element not exists.
        BstNode newBstNode = new BstNode(element, parent);
        if (cmp > 0) {
            parent.right = newBstNode;
        } else {
            parent.left = newBstNode;
        }
        size++;
    }

    /**
     * 比较两个元素的大小
     */
    private int compare(T e1, T e2) {
        return (comparator != null)
                ? comparator.compare(e1, e2)
                : ((Comparable) e1).compareTo(e2);
    }


    @Override
    public BstNode root() {
        return root;
    }

    @Override
    public BstNode left(Object node) {
        return ((BstNode) node).left;
    }

    @Override
    public BstNode right(Object node) {
        return ((BstNode) node).right;
    }

    @Override
    public T data(Object node) {
        return ((BstNode) node).element;
    }

}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy