Java建立二叉排序树
public class Bst {
class Node {
int data;
Node left;
Node right;
public Node(int data) {
this.data = data;
this.left=null;
this.right = null;
}
}
Node root;
public Bst() {
root = null;
}
public void BuildBST(int i) {
Node newNode = new Node(i);
if (root==null) {
root = newNode;
} else {
Node current = root;
Node parent;
while (true) {
parent = current;
if (i<current.data) {
current = current.left;
if (current==null) {
parent.left=newNode;
return;
}
}else {
current = current.right;
if (current==null) {
parent.right=newNode;
return ;
}
}
}
}
}
public void inOrder(Node root) {
if (root!=null) {
inOrder(root.left);
System.out.println(root.data);
inOrder(root.right);
}
}
public void inOrder() {
this.inOrder(this.root);
}
public static void main(String[] args) {
Bst bst = new Bst();
int[] array = {7,9,10,1,0,27,33,45,78,6};
for(int i=0;i<array.length;i++) {
bst.BuildBST(array[i]);
}
bst.inOrder();
}
}