二叉排序树

二叉排序树

二叉查找树、二叉搜索树 BST;对于二叉树中的任何非叶子节点 要求左子节点比当前节点值小,右子节点比当前节点值大。

实现
/**
 * @Description 二叉排序树的节点
 * @auther Eleven
 * @create 2020-04-09 20:43
 **/
public class Node {
    int value;
    Node left;
    Node right;
    public Node(int value) {
        this.value = value;
    }
    //添加方法
    public void add(Node node) {
        if (node==null){
            return;
        }
        if (this.value>node.value){
            if (this.left==null){
                this.left =node;
            }else {
                this.left.add(node);
            }
        }else {
            if (this.right==null){
                this.right =node;
            }else {
                this.right.add(node);
            }
        }
    }
    //中序遍历
    public void midPrint(Node root) {
        if (root == null){
            return;
        }
        midPrint(root.left);
        System.out.println(root.value);
        midPrint(root.right);
    }
}
/**
 * @Description 二叉排序树
 * @auther Eleven
 * @create 2020-04-09 20:43
 **/
public class BinarySortTree {
    Node root;

    public void  add(Node node){
        if (root == null ){
            root=node;
        }else{
            root.add(node);
        }
    }
    public void midPrint() {
        if (root !=null){
            root.midPrint(root);
        }
    }
}
//测试方法
 public static void main(String[] args) {
        BinarySortTree binarySortTree = new BinarySortTree();
        int[] arr = new int[]{7,2,10,12,5,1,9};
        for (int i:arr){
            binarySortTree.add(new Node(i));
        }
        binarySortTree.midPrint();
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值