搜索树的总结及其查找、插入操作详解与代码--Java

搜索树
1.搜索的两种模型:
  • 纯Key模型: 即我们 Set 要解决的事情,只需要判断关键字在不在集合中即可,没有关联的 value
  • Key-Value模型: 即我们 Map 要解决的事情,需要根据指定 Key 找到关联的 Value
 
2.搜索的结构
  • 搜索树
  • 哈希表
  • 跳表(了解)
Java中:
  • Map
  • Set

搜索树:
1.概念:
  二叉搜索树又称二叉排序树,它或者是一棵空树 ** ,或者是具有以下性质的二叉树 :
2.搜索树特点
  • 特殊的树(二叉搜索树 重点)
  • 纯Key模型
  • 搜索树的中序遍历是有序的(特点)
  • Key不允许重复
 
3.操作:
  • 查找/搜索
  • 插入
  • 删除
 
package 搜索树;

/**
 * Create with Darcula IDEA
 * Description:
 */
public class BinarySearchTree {
    public static class Node {
        private int key;
        private Node right;
        private Node left;

        Node(int key){
            this.key = key;
        }
    }
    private Node root = null;
    /**在搜索树中查找 key,如果找到,返回 key 所在的结点,否则返回 null
     * *@param key
     *  @return
     */
    public Node search(int key){
       Node cur = root;
        while(cur != null){
            if(key == cur.key){
                return cur;
            }else if(key > cur.key){
                cur = cur.right;
            }else{
                cur = cur.right;
            }
        }
        return null;
    }
    /**插入
     * @param key
     * @return true 表示插入成功, false 表示插入失败
     */
    public boolean insert(int key){
//        1. 如果树为空树,即根 == null,直接插入
        if(root == null){
            root = new Node(key);
            return true;
        }
//        2. 如果树不是空树,按照查找逻辑确定插入位置,插入新结点
        Node cur = root;
        Node parent = null;
        while(cur != null){
            if(key > cur.key){
                parent = cur;
                cur = cur.right;
            }else if(key == cur.key){
                return false;
            }else{
                parent = cur;
                cur = cur.left;
            }
        }
        //插入新结点
        Node node = new Node(key);
        if(key > parent.key){
            parent.right = node;
        }else{
            parent.left = node;
        }
        return true;
    }
}

 

 
 
 
 
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值