通俗易懂的二叉排序树

138 阅读1分钟

定义

  • 左子树的节点值<根节点值<右子树的节点值
  • 对二叉排序树的中序遍历即是递增的有序序列

二叉查找树的查找

递归查找
BiTree search(BiTree t,key){
    if (t == null) {
        return null;
    }
    if (t.data == key) {
        return t;
    }else if (t.data > key) {
        return search(t.lChild() ,key);
    }else {
        return search(t.rChild() ,key);
    }
}
非递归查找
BiTree search(BiTree t,key){
    while(t != null && t.data != key) {
        if (t.data>key){
            t = t.lChild();
        }else {
            t = t.rChild();
        }
    }
    return t;
}

二叉查找树的插入

boolean insert(BiTree t ,key){
    if(t == null) {
        BiTree temp = new BiTree();
        temp.data = key;
        t = temp;
        return true;
    }
    if (t.data == key) {
        return false;
    }else if (t.data > key) {
        insert(t.lChild() ,key);
    }else {
        insert(t.rChild() ,key);
    }
}