图解:二叉搜索树算法(BST)

2024-05-13 01:08
文章标签 算法 搜索 图解 二叉 bst

本文主要是介绍图解:二叉搜索树算法(BST),希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

摘要: 原创出处:www.bysocket.com 泥瓦匠BYSocket 希望转载,保留摘要,谢谢!“岁月极美,在于它必然的流逝”“春花 秋月 夏日 冬雪”— 三毛

一、树 & 二叉树

是由节点和边构成,储存元素的集合。节点分根节点、父节点和子节点的概念。如图:树深=4; 5是根节点;同样8与3的关系是父子节点关系。

1

二叉树binary tree,则加了“二叉”(binary),意思是在树中作区分。每个节点至多有两个子(child),left child & right child。二叉树在很多例子中使用,比如二叉树表示算术表达式。如图:1/8是左节点;2/3是右节点;

2

二、二叉搜索树 BST

顾名思义,二叉树上又加了个搜索的限制。其要求:每个节点比其左子树元素大,比其右子树元素小。如图:每个节点比它左子树的任意节点大,而且比它右子树的任意节点小

3

三、BST Java实现

直接上代码,对应代码分享在 Github 主页BinarySearchTree.java
package org.algorithm.tree;
/** Copyright [2015] [Jeff Lee]** Licensed under the Apache License, Version 2.0 (the "License");* you may not use this file except in compliance with the License.* You may obtain a copy of the License at**   http://www.apache.org/licenses/LICENSE-2.0** Unless required by applicable law or agreed to in writing, software* distributed under the License is distributed on an "AS IS" BASIS,* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.* See the License for the specific language governing permissions and* limitations under the License.*//*** 二叉搜索树(BST)实现** Created by bysocket on 16/7/7.*/
public class BinarySearchTree {/*** 根节点*/public static TreeNode root;public BinarySearchTree() {this.root = null;}/*** 查找*      树深(N) O(lgN)*      1. 从root节点开始*      2. 比当前节点值小,则找其左节点*      3. 比当前节点值大,则找其右节点*      4. 与当前节点值相等,查找到返回TRUE*      5. 查找完毕未找到,* @param key* @return*/public TreeNode search (int key) {TreeNode current = root;while (current != null&& key != current.value) {if (key < current.value )current = current.left;elsecurrent = current.right;}return current;}/*** 插入*      1. 从root节点开始*      2. 如果root为空,root为插入值*      循环:*      3. 如果当前节点值大于插入值,找左节点*      4. 如果当前节点值小于插入值,找右节点* @param key* @return*/public TreeNode insert (int key) {// 新增节点TreeNode newNode = new TreeNode(key);// 当前节点TreeNode current = root;// 上个节点TreeNode parent  = null;// 如果根节点为空if (current == null) {root = newNode;return newNode;}while (true) {parent = current;if (key < current.value) {current = current.left;if (current == null) {parent.left = newNode;return newNode;}} else {current = current.right;if (current == null) {parent.right = newNode;return newNode;}}}}/*** 删除节点*      1.找到删除节点*      2.如果删除节点左节点为空 , 右节点也为空;*      3.如果删除节点只有一个子节点 右节点 或者 左节点*      4.如果删除节点左右子节点都不为空* @param key* @return*/public TreeNode delete (int key) {TreeNode parent  = root;TreeNode current = root;boolean isLeftChild = false;// 找到删除节点 及 是否在左子树while (current.value != key) {parent = current;if (current.value > key) {isLeftChild = true;current = current.left;} else {isLeftChild = false;current = current.right;}if (current == null) {return current;}}// 如果删除节点左节点为空 , 右节点也为空if (current.left == null && current.right == null) {if (current == root) {root = null;}// 在左子树if (isLeftChild == true) {parent.left = null;} else {parent.right = null;}}// 如果删除节点只有一个子节点 右节点 或者 左节点else if (current.right == null) {if (current == root) {root = current.left;} else if (isLeftChild) {parent.left = current.left;} else {parent.right = current.left;}}else if (current.left == null) {if (current == root) {root = current.right;} else if (isLeftChild) {parent.left = current.right;} else {parent.right = current.right;}}// 如果删除节点左右子节点都不为空else if (current.left != null && current.right != null) {// 找到删除节点的后继者TreeNode successor = getDeleteSuccessor(current);if (current == root) {root = successor;} else if (isLeftChild) {parent.left = successor;} else {parent.right = successor;}successor.left = current.left;}return current;}/*** 获取删除节点的后继者*      删除节点的后继者是在其右节点树种最小的节点* @param deleteNode* @return*/public TreeNode getDeleteSuccessor(TreeNode deleteNode) {// 后继者TreeNode successor = null;TreeNode successorParent = null;TreeNode current = deleteNode.right;while (current != null) {successorParent = successor;successor = current;current = current.left;}// 检查后继者(不可能有左节点树)是否有右节点树// 如果它有右节点树,则替换后继者位置,加到后继者父亲节点的左节点.if (successor != deleteNode.right) {successorParent.left = successor.right;successor.right = deleteNode.right;}return successor;}public void toString(TreeNode root) {if (root != null) {toString(root.left);System.out.print("value = " + root.value + " -> ");toString(root.right);}}
}/*** 节点*/
class TreeNode {/*** 节点值*/int value;/*** 左节点*/TreeNode left;/*** 右节点*/TreeNode right;public TreeNode(int value) {this.value = value;left  = null;right = null;}
}

1. 节点数据结构首先定义了节点的数据接口,节点分左节点和右节点及本身节点值。如图

4

代码如下:

/*** 节点*/
class TreeNode {/*** 节点值*/int value;/*** 左节点*/TreeNode left;/*** 右节点*/TreeNode right;public TreeNode(int value) {this.value = value;left  = null;right = null;}
}

 2. 插入插入,和删除一样会引起二叉搜索树的动态变化。插入相对删处理逻辑相对简单些。如图插入的逻辑:5

a. 从root节点开始b.如果root为空,root为插入值c.循环:d.如果当前节点值大于插入值,找左节点e.如果当前节点值小于插入值,找右节点代码对应:

    /*** 插入*      1. 从root节点开始*      2. 如果root为空,root为插入值*      循环:*      3. 如果当前节点值大于插入值,找左节点*      4. 如果当前节点值小于插入值,找右节点* @param key* @return*/public TreeNode insert (int key) {// 新增节点TreeNode newNode = new TreeNode(key);// 当前节点TreeNode current = root;// 上个节点TreeNode parent  = null;// 如果根节点为空if (current == null) {root = newNode;return newNode;}while (true) {parent = current;if (key < current.value) {current = current.left;if (current == null) {parent.left = newNode;return newNode;}} else {current = current.right;if (current == null) {parent.right = newNode;return newNode;}}}}

 3.查找其算法复杂度 : O(lgN),树深(N)。如图查找逻辑:

6

a.从root节点开始b.比当前节点值小,则找其左节点c.比当前节点值大,则找其右节点d.与当前节点值相等,查找到返回TRUEe.查找完毕未找到代码对应:

    /*** 查找*      树深(N) O(lgN)*      1. 从root节点开始*      2. 比当前节点值小,则找其左节点*      3. 比当前节点值大,则找其右节点*      4. 与当前节点值相等,查找到返回TRUE*      5. 查找完毕未找到,* @param key* @return*/public TreeNode search (int key) {TreeNode current = root;while (current != null&& key != current.value) {if (key < current.value )current = current.left;elsecurrent = current.right;}return current;}

4. 删除首先找到删除节点,其寻找方法:删除节点的后继者是在其右节点树种最小的节点。如图删除对应逻辑:7

结果为:

8

a.找到删除节点b.如果删除节点左节点为空 , 右节点也为空;c.如果删除节点只有一个子节点 右节点 或者 左节点d.如果删除节点左右子节点都不为空代码对应见上面完整代码。 案例测试代码如下,BinarySearchTreeTest.java

package org.algorithm.tree;
/** Copyright [2015] [Jeff Lee]** Licensed under the Apache License, Version 2.0 (the "License");* you may not use this file except in compliance with the License.* You may obtain a copy of the License at**   http://www.apache.org/licenses/LICENSE-2.0** Unless required by applicable law or agreed to in writing, software* distributed under the License is distributed on an "AS IS" BASIS,* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.* See the License for the specific language governing permissions and* limitations under the License.*//*** 二叉搜索树(BST)测试案例 {@link BinarySearchTree}** Created by bysocket on 16/7/10.*/
public class BinarySearchTreeTest {public static void main(String[] args) {BinarySearchTree b = new BinarySearchTree();b.insert(3);b.insert(8);b.insert(1);b.insert(4);b.insert(6);b.insert(2);b.insert(10);b.insert(9);b.insert(20);b.insert(25);// 打印二叉树b.toString(b.root);System.out.println();// 是否存在节点值10TreeNode node01 = b.search(10);System.out.println("是否存在节点值为10 => " + node01.value);// 是否存在节点值11TreeNode node02 = b.search(11);System.out.println("是否存在节点值为11 => " + node02);// 删除节点8TreeNode node03 = b.delete(8);System.out.println("删除节点8 => " + node03.value);b.toString(b.root);}
}
运行结果如下:
value = 1 -> value = 2 -> value = 3 -> value = 4 -> value = 6 -> value = 8 -> value = 9 -> value = 10 -> value = 20 -> value = 25 -> 
是否存在节点值为10 => 10
是否存在节点值为11 => null
删除节点8 => 8
value = 1 -> value = 2 -> value = 3 -> value = 4 -> value = 6 -> value = 9 -> value = 10 -> value = 20 -> value = 25 ->

四、小结

与偶尔吃一碗“老坛酸菜牛肉面”一样的味道,品味一个算法,比如BST,的时候,总是那种说不出的味道。树,二叉树的概念BST算法相关代码分享在 Github 主页

如以上文章或链接对你有帮助的话,别忘了在文章结尾处评论哈~ 你也可以点击页面右边“分享”悬浮按钮哦,让更多的人阅读这篇文章。

这篇关于图解:二叉搜索树算法(BST)的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/984253

相关文章

HTML5 搜索框Search Box详解

《HTML5搜索框SearchBox详解》HTML5的搜索框是一个强大的工具,能够有效提升用户体验,通过结合自动补全功能和适当的样式,可以创建出既美观又实用的搜索界面,这篇文章给大家介绍HTML5... html5 搜索框(Search Box)详解搜索框是一个用于输入查询内容的控件,通常用于网站或应用程

使用雪花算法产生id导致前端精度缺失问题解决方案

《使用雪花算法产生id导致前端精度缺失问题解决方案》雪花算法由Twitter提出,设计目的是生成唯一的、递增的ID,下面:本文主要介绍使用雪花算法产生id导致前端精度缺失问题的解决方案,文中通过代... 目录一、问题根源二、解决方案1. 全局配置Jackson序列化规则2. 实体类必须使用Long封装类3.

Springboot实现推荐系统的协同过滤算法

《Springboot实现推荐系统的协同过滤算法》协同过滤算法是一种在推荐系统中广泛使用的算法,用于预测用户对物品(如商品、电影、音乐等)的偏好,从而实现个性化推荐,下面给大家介绍Springboot... 目录前言基本原理 算法分类 计算方法应用场景 代码实现 前言协同过滤算法(Collaborativ

openCV中KNN算法的实现

《openCV中KNN算法的实现》KNN算法是一种简单且常用的分类算法,本文主要介绍了openCV中KNN算法的实现,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的... 目录KNN算法流程使用OpenCV实现KNNOpenCV 是一个开源的跨平台计算机视觉库,它提供了各

springboot+dubbo实现时间轮算法

《springboot+dubbo实现时间轮算法》时间轮是一种高效利用线程资源进行批量化调度的算法,本文主要介绍了springboot+dubbo实现时间轮算法,文中通过示例代码介绍的非常详细,对大家... 目录前言一、参数说明二、具体实现1、HashedwheelTimer2、createWheel3、n

SpringBoot实现MD5加盐算法的示例代码

《SpringBoot实现MD5加盐算法的示例代码》加盐算法是一种用于增强密码安全性的技术,本文主要介绍了SpringBoot实现MD5加盐算法的示例代码,文中通过示例代码介绍的非常详细,对大家的学习... 目录一、什么是加盐算法二、如何实现加盐算法2.1 加盐算法代码实现2.2 注册页面中进行密码加盐2.

Java时间轮调度算法的代码实现

《Java时间轮调度算法的代码实现》时间轮是一种高效的定时调度算法,主要用于管理延时任务或周期性任务,它通过一个环形数组(时间轮)和指针来实现,将大量定时任务分摊到固定的时间槽中,极大地降低了时间复杂... 目录1、简述2、时间轮的原理3. 时间轮的实现步骤3.1 定义时间槽3.2 定义时间轮3.3 使用时

如何通过Golang的container/list实现LRU缓存算法

《如何通过Golang的container/list实现LRU缓存算法》文章介绍了Go语言中container/list包实现的双向链表,并探讨了如何使用链表实现LRU缓存,LRU缓存通过维护一个双向... 目录力扣:146. LRU 缓存主要结构 List 和 Element常用方法1. 初始化链表2.

Python使用DeepSeek进行联网搜索功能详解

《Python使用DeepSeek进行联网搜索功能详解》Python作为一种非常流行的编程语言,结合DeepSeek这一高性能的深度学习工具包,可以方便地处理各种深度学习任务,本文将介绍一下如何使用P... 目录一、环境准备与依赖安装二、DeepSeek简介三、联网搜索与数据集准备四、实践示例:图像分类1.

golang字符串匹配算法解读

《golang字符串匹配算法解读》文章介绍了字符串匹配算法的原理,特别是Knuth-Morris-Pratt(KMP)算法,该算法通过构建模式串的前缀表来减少匹配时的不必要的字符比较,从而提高效率,在... 目录简介KMP实现代码总结简介字符串匹配算法主要用于在一个较长的文本串中查找一个较短的字符串(称为