二叉排序树(二叉搜索树)

一、二叉排序树概述

二叉排序树(Binary Sort Tree),又称二叉查找树(Binary Search Tree),亦称二叉搜索树。对于二叉排序树的任何一个非叶子节点,要求左子节点的值比当前节点的值小右子节点的值比当前节点的值大(如果有相同的值,则该节点放在左子节点或右子节点都可)。在一般情况下,二叉排序树的查询效率比链表结构要高。

如下图所示就是一个二叉排序树:

在这里插入图片描述

二、二叉排序树的基本操作

2.1 创建和遍历二叉排序树

【案例描述】

给定如下数组:

arr = {
   7, 3, 10, 12, 5, 1, 9}

其二叉排序树如下图所示:

在这里插入图片描述

要求:

  1. 创建二叉排序树
  2. 中序遍历二叉排序树

【代码实现】

/**
 * @Description 创建和遍历二叉排序树
 */
public class No1_BinarySortTree {
   
    public static void main(String[] args) {
   
        int[] arr = {
   7, 3, 10, 12, 5, 1, 9};
        BinarySortTree tree = new BinarySortTree(null);
        for (int item : arr){
   
            tree.addNode(tree.new Node(item));  // 添加节点
        }
        tree.preOrder();  // 前序遍历
    }
}

class BinarySortTree{
   
    private Node root;  // 根节点

    public BinarySortTree(Node node){
   
        this.root = node;
    }
    // 添加节点到二叉排序树中
    public void addNode(Node node){
   
        if (root == null){
   
            root = node;
        }else{
   
            root.addNode(node);
        }
    }
    // 中序遍历:左根右
    public void preOrder(){
   
        if (root != null){
   
            root.preOrder();
        }
    }

    /**
     * 内部类:节点
     */
    class Node{
   
        int value;
        Node left;  // 指向左子节点
        Node right; // 指向右子节点

        public Node(int value){
   
            this.value = value;
        }
        // 添加节点到二叉排序树中
        public void addNode(Node node)
  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值