构造二叉查找树
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;
}
}
}