BST插入與查找

B樹: 二叉查找樹,全部左節點都比父節點要小,全部右節點都比父節點要大。查找,插入的時間複雜度爲O(logn)node

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;
        }
    }
}
相關文章
相關標籤/搜索