使用java建立二叉查找树
/**
* java 建立 二叉查找树
*/
public Node build(Node root,int temp) {
if(root==null) {
Node node = new Node();
node.data=temp;
node.left=null;
node.right=null;
return node;
}
if(temp>root.data) {
root.right=build(root.right,temp);
}else {
root.left=build(root.left,temp);
}
return root;
}
public void search(Node present) {
if(present==null) {
return ;
}
System.out.println(present.data);
search(present.left);
search(present.right);
}
@Test
public void BinarySerachTree() {
System.out.println("输入 n:");
Scanner scan = new Scanner(System.in);
int n=scan.nextInt();
System.out.println("输入 n 个整数:");
Node head=null;
for(int i=1;i<=n;i++) {
int temp=scan.nextInt();
head=build(head,temp);
}
System.out.println("二叉树:");
search(head);
System.out.println("搜索结束");
}
Node 类
class Node{
int data;
Node left;
Node right;
}