BinarySearchTree(二分查找树)

Don’t say much, just go to the code.

package org.bood.tree;

/**
 * 二分查找树
 * ps:如果 data[0] 等于一组数据中最小的,那么就会增加查找的时间复杂度。
 * 平衡二叉树(追求极致的平衡),现实需求很难满足,红黑数孕育而生
 *
 * @author bood
 * @since 2020/10/16
 */
public class BinarySearchTree {

    /**
     * 根节点数
     */
    int data;
    /**
     * 添加一个计数器来记录重复数据的出现次数
     */
    int count;
    /**
     * 左子树
     */
    BinarySearchTree left;
    /**
     * 右子树
     */
    BinarySearchTree right;

    public BinarySearchTree(int data) {
        this.data = data;
        // 初始化为1,表示至少有一个这样的值
        this.count = 1;
        this.left = null;
        this.right = null;
    }

    /**
     * 插入新节点到二分查找树
     * 如果新节点的值小于当前节点的值,则插入到左子树;
     * 如果大于,则插入到右子树;
     * 如果等于,可以选择忽略或者记录重复次数。
     *
     * @param newData 新节点的值
     * @author bood
     * @since 2024/01/05
     */
    public void insert(int newData) {
        if (newData > this.data) {
            if (this.right == null) {
                this.right = new BinarySearchTree(newData);
            } else {
                this.right.insert(newData);
            }
        } else if (newData < this.data) {
            if (this.left == null) {
                this.left = new BinarySearchTree(newData);
            } else {
                this.left.insert(newData);
            }
        } else {
            // 如果 newData 等于 this.data,增加这个节点的计数
            this.count++;
        }
    }

    /**
     * 对二分查找树进行中序遍历
     * 中序遍历的结果为排序后的节点值
     *
     * @author bood
     * @since 2024/01/05
     */
    public void inOrderTraversal() {
        if (this.left != null) {
            this.left.inOrderTraversal();
        }
        // 打印节点值及其出现的次数
        System.out.print(this.data + "(" + this.count + ") ");
        if (this.right != null) {
            this.right.inOrderTraversal();
        }
    }

    public static void main(String[] args) {
        int[] data = {5, 6, 1, 7, 8, 9, 2, 4, 10};
        BinarySearchTree bst = new BinarySearchTree(data[0]);

        for (int i = 1; i < data.length; i++) {
            bst.insert(data[i]);
        }

        System.out.println("中序遍历:");
        bst.inOrderTraversal();
    }
    
}
  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值