二叉排序树的创建与添加

package demo1;

public class BinarySortTree {
    public static void main(String[] args) {
        //测试
        int[] arr = {7,3,10,12,5,1,9};
        CreatTree creatTree = new CreatTree();
        for (int i = 0; i < arr.length; i++) {
            creatTree.addTree(new Node(arr[i]));
        }
        creatTree.showTree();
    }
}

//创建二叉排序树
class CreatTree{
    private Node root;
    //添加树
    public void addTree(Node node){
        if (root == null){
            root = node;
        }else {
            root.add(node);
        }
    }
    //遍历树
    public void showTree(){
        root.midList();
    }
}

//创建节点
class Node{
    private int value;
    Node left;
    Node right;

    public Node(int value) {
        this.value = value;
    }
    public Node() {
    }

    public int getValue() {
        return value;
    }

    public void setValue(int value) {
        this.value = value;
    }

    @Override
    public String toString() {
        return "Node{" +
                "value=" + value +
                '}';
    }

    //添加节点
    public void add(Node node){
        if (node == null){
            return;
        }
        if (node.value < this.value){
            if (this.left == null){
                this.left = node;
            }else {
                this.left.add(node);
            }
        }else if (node.value >= this.value){
            if (this.right == null){
                this.right = node;
            }else {
                this.right.add(node);
            }
        }
    }

    //中序遍历节点
    public void midList(){
        if (this.left != null){
            this.left.midList();
        }
        System.out.println(this);
        if (this.right != null){
            this.right.midList();
        }
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值