二叉树系列---构造二叉查找树

构造二叉查找树

package binary_tree;

public class BuildBinarySearchTree {

    private Node root;

    public BuildBinarySearchTree(){
        root=null;
    }

    public void insert(int data){
        Node newNode=new Node(data);
        if(root==null){
            root=newNode;
        }else{
            Node current=root;
            Node parent=root;
            while(true){
                parent=current;
                if(newNode.value<current.value){
                    current=current.left;
                    if(current==null){
                        parent.left=newNode;
                        return;
                    }
                }else{
                    current=current.right;
                    if(current==null){
                        parent.right=newNode;
                        return;
                    }
                }
            }
        }

    }

    public void buildTree(int[] data){
        for(int i=0;i<data.length;i++){
            insert(data[i]);
        }
    }


    public void inOrder(Node node){
        if(node!=null){
            inOrder(node.left);
            System.out.print(node.value+" ");
            inOrder(node.right);
        }
    }

    /** * @param args */
    public static void main(String[] args) {
        BuildBinarySearchTree BT=new BuildBinarySearchTree();
        int[] data={2,8,7,4,9,3,1,6,7,5};
        BT.buildTree(data);
        BT.inOrder(BT.root);
    }


    class Node{
        int value;
        Node left;
        Node right;

        public Node(int data){
            this.value=data;
            this.left=null;
            this.right=null;
        }
    }

}
    原文作者:二叉查找树
    原文地址: https://blog.csdn.net/bh_xiaoxinba/article/details/53006830
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞