BST的创建于遍历【java】

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();
        }
    }

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值