BST插入与查找

B树: 二叉查找树,所有左节点都比父节点要小,所有右节点都比父节点要大。查找,插入的时间复杂度为O(logn)

public class BTreeTest {
    public static  int[] arrays = {1,7,5,12,8,4};
    private  static Node header;
    public static void main(String[] args){
        buildBTree(); //构建B树
        middleTravers(header); //中序遍历
        System.out.println(search(1,header));
        System.out.println(search(10,header));
    }
    
    private static  void buildBTree(){
        for(Integer i : arrays){
            if(null == header) {
                header = new Node(i);
            }else{
                insert(header,i);
            }
        }
    }
    
    private static void insert(Node n,int i){
        int value = n.value;
        if(value >= i){
            if(null == n.leftChildNode){
                n.leftChildNode = new Node(i);
            }else{
                insert(n.leftChildNode,i);
            }    
        }else{
            if(null == n.rightChildNode){
                n.rightChildNode = new Node(i);
            }else{
                insert(n.rightChildNode,i);
            }    
        }
    }
    
    private static boolean search(int i,Node node){
        if(null == node) return false;
        if(node.value > i){
            return search(i, node.leftChildNode);            
        }else if(node.value < i){
            return search(i, node.rightChildNode);                        
        }
        return true;
    }
    
    private static void middleTravers(Node node){
        if(null == node) return;
        middleTravers(node.leftChildNode);
        System.out.print(node.value);
        middleTravers(node.rightChildNode);
    }
    
    private static class Node{
        public int value;
        public Node leftChildNode; //左节点
        public Node rightChildNode;//右节点
        
        public Node(int i){
            value = i;
        }
    }
}

 

posted @ 2015-04-12 18:57  huliangbin  阅读(211)  评论(0编辑  收藏  举报