二分搜索树实现查找最大值和最小值的的递归与非递归实现

    //寻找二分搜索树的最小值 (递归实现)
    public E minimum() {
        if (size == 0) {
            throw new IllegalArgumentException("BST is empty!");
        }
        return minimum(root).e;
    }

    private Node minimum(Node node) {
        if (node.left == null) {
            return node;
        }

        return minimum(node.left);
    }


    //寻找二分搜索树的最大值 (递归实现)
    public E maximum() {
        if (size == 0) {
            throw new IllegalArgumentException("BST is empty");
        }
        return maximum(root).e;
    }

    private Node maximum(Node node) {
        if (node.right == null) {
            return node;
        }
        return maximum(node.right);
    }


    //寻找二分搜索树的最小值 (非递归实现)
    public E minimumNR() {
        if (size == 0) {
            throw new IllegalArgumentException("BST is empty");
        }
        Node cur = root;
        while (cur.left != null) {
            cur = cur.left;
        }
        return cur.e;
    }


    //寻找二分搜索树的最大值 (非递归实现)
    public E maximumNR() {
        if (size == 0) {
            throw new IllegalArgumentException("BST is empty");
        }
        Node cur = root;
        while (cur.right != null) {
            cur = cur.right;
        }
        return cur.e;
    }

 

你可能感兴趣的:(java,数据结构,二分搜索树)