import org.jetbrains.annotations.NotNull;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class BST {
public static void main(String[] args){
List<Integer> nodes = new ArrayList<Integer>();//如何定义数组
Scanner scanner = new Scanner(System.in);//如何接收输入
int a = scanner.nextInt();
while( a != -1 ) {
nodes.add(a);//如何给数组中添加元素
a = scanner.nextInt();
}
System.out.println(nodes);
Node first = new Node();
System.out.println("创建BST中....");
create_BST(nodes,first);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("访问结点:");
visit_BST(first);
}
public static void create_BST(List<Integer> nodes, Node head){
int i = 0;
while( i < nodes.size() ){
BST_insert(nodes.get(i),head);
i++;
}
}
public static void BST_insert(Integer data,@NotNull Node head){
if( head.data == -1 ){
head.data = data;
System.out.println(data+"插入成功");
return ;
}
if( data == head.data ){
System.out.println(data+"插入失败");
}
//不能传进null指针在函数里null,这个思路对原来的对象不起作用,也就是说,原来的对象还是null
//应该在函数中Null一个新的对象,然后把这个对象挂载到原来的对象上
else if(data < head.data){//如何递归的生成二叉树
if( head.left == null ){
Node temp = new Node();
head.left = temp;
}
BST_insert(data,head.left);
}
else{
if( head.right == null ){
Node temp = new Node();
head.right = temp;
}
BST_insert(data,head.right);
}
}
public static void visit_BST(@NotNull Node head){
if( head.left != null )
visit_BST(head.left);
visit(head);
if( head.right != null )
visit_BST(head.right);
//不能用while,因为如果用while的话,对于第一层来说head这个结点是固定死的,
//也就是说head.left一直都不为Null,会出现死循环,应该把while改为if即可
// while( head.left != null ) visit_BST(head.left);
// visit(head);
// while( head.right != null ) visit_BST(head.right);
}
public static void visit(Node head){
System.out.println(head.data);
try{
Thread.sleep(500);
}
catch (InterruptedException e){
e.printStackTrace();
}
}
}
BST的创建于遍历【java】
最新推荐文章于 2023-01-09 16:11:14 发布