Board logo

标题: 二叉查找树实现原理分析(6) [打印本页]

作者: look_w    时间: 2019-1-11 18:31     标题: 二叉查找树实现原理分析(6)

floor和ceiling的实现

floor的实现

floor()要实现的就是向下取整,我们来分析一下它的执行流程:



二叉树floor流程图

具体实现代码如下:

/**
* Returns the largest key in the symbol table less than or equal to key.
*
* @param  key the key
* @return the largest key in the symbol table less than or equal to key
* @throws NoSuchElementException if there is no such key
* @throws IllegalArgumentException if  key is null
*/
public Key floor(Key key) {
    if (key == null) {
        throw new IllegalArgumentException("argument to floor() is null");
    }
    if (isEmpty()) {
        throw new NoSuchElementException("called floor() with empty symbol table");
    }
    Node x = floor(root, key);
    if (x == null) {
        return null;
    } else {
        return x.key;
    }
}
private Node floor(Node x, Key key) {
    if (x == null) {
        return null;
    } else {
        int cmp = key.compareTo(x.key);
        if(cmp == 0) {
            return x;
        } else if(cmp < 0) {
            return floor(x.left, key);
        } else {
            Node t = floor(x.right, key);
            if(t != null) {
                return t;
            } else {
                return x;
            }
        }
    }
}





欢迎光临 电子技术论坛_中国专业的电子工程师学习交流社区-中电网技术论坛 (http://bbs.eccn.com/) Powered by Discuz! 7.0.0