BinarySearchTree

//建立内部类Node,Node表明的就是树节点
public static class Node{
    int key;
    Node leftChild;
    Node rightChild;

    public Node(int key){
        this.key=key;
        this.leftChild=null;
        this.rightChild=null;
    }

    public Node(int key,Node leftChild,Node rightChild){
        this.key=key;
        this.leftChild=leftChild;
        this.rightChild=rightChild;
    }


    public int getKey(){
        return key;
    }

    @Override
    public boolean  equals(Object o){
        Node node=(Node)o;
        return getKey() == node.key;
    }

    public Node left(){
        return this.leftChild;
    }

    public Node right(){
        return this.rightChild;
    }
}

//成员变量以及构造函数
public Node root;
public BinarySearchTree(){
    root=null;
}

public boolean isEmpty(){
    return root == null ? true : false;
}

public void makeEmpty(){
    this.root=null;
}

public boolean contains(int target,Node node){
    if(node == null || isEmpty()){
        return false;
    }
    if(target<node.key){
        return contains(target, node.leftChild);
    }else if(target>node.key){
        return contains(target,node.rightChild);
    }else{
        return true;
    }
}

public Node findMin(Node node){
    if(node==null || isEmpty()){
        return null;
    }
    if(node!=null && node.leftChild!=null) {
        return findMin(node.leftChild);
    }else{
        return node;
    }
}

public Node findMax(Node node){
    if(node==null || isEmpty()){
        return null;
    }
    //这就是返回条件(递归结束条件)
    if(node.rightChild == null)
        return node;
    return findMax(node.rightChild);
}

//总体思路就是插入哪个节点,就返回哪个节点
public Node insert(int key,Node node){

    if(node==null){
        //用于真实生成节点(递归结束条件)
        return new Node(key,null,null);
    }else if(key < node.key){
        //用于创建与左节点间的关联
        node.leftChild=insert(key, node.leftChild);
    }else if(key > node.key){
        //用于创建与右节点间的关联
        node.rightChild=insert(key, node.rightChild);
    }else ;

    return node;
}

public void insert(int key){
    root=insert(key,root);
}
//思路与插入思路差很少,删除那个节点就返回哪个节点
public Node remove(int key,Node node){

    if(node == null) return null;
    if(key < node.key){
        node.leftChild=remove(key, node.leftChild);
    }else if(key > node.key){
        node.rightChild=remove(key, node.rightChild);
    }
    //左右子树均非空
    else if(node.leftChild != null && node.rightChild != null){
        //找到要移动的节点并替换掉,该过程出现新一轮的树枝生成过程
        node.key=findMin(root.rightChild).key;
        //这里负责新树枝的生成,由于这里要移动的是该节点的右分支,因此其实永远不会有删除动做发生,只会发生一点树枝的移动动做
        node.rightChild=remove(node.key, node.rightChild);
    }
    //左子树或者右子树为空,此时node节点即为要删除的节点或者不存在的删除节点
    else{
        node = (node.rightChild == null) ? node.leftChild : node.rightChild;
    }

    return node;
}

public void remove(int key){
    root=remove(key, root);
}

以上就简单介绍了二人查找数的基本操做,固然用的是递归实现,可是也能够用到非递归的方法,这里再也不给出。java

相关文章
相关标签/搜索