算法--查找--二叉排序树创建、查找
来源:互联网 发布:酒精漱口 知乎 编辑:程序博客网 时间:2024/05/17 01:25
二叉排序树(BST)具有如下性质:
(1)若有左子树,左子树所有值均小于根节点的值;
(2)若有右子树,右子树所有值均大于根节点的值;
(3)左右子树,分别是一棵二叉排序树。左子树中最右边节点必然是左子树中最大的,右子树最左边节点必然是右子树中最小的。
BST的创建和搜索还是比较简单的,思路基本一样,有树便有递归。比较棘手的是它的删除,相比于C语言的指针操作来说,java的赋值引用在此时就显得比较鸡肋,实现起来相对麻烦,待后续更新。
条件:
树上节点不能重复
原理:
二叉树的性质决定数据排布规律
实现:
一贯的原则,在保证尽量简洁的前提下,能上代码就不说话。
先附上一个工具类,主要用来遍历。
public class TreeUtils { public static void fir(Node node) { if (node != null) { System.out.print(node.data + " "); fir(node.left); fir(node.right); } } public static void mid(Node node) { if (node != null) { mid(node.left); System.out.print(node.data + " "); mid(node.right); } } public static void las(Node node) { if (node != null) { las(node.left); las(node.right); System.out.print(node.data + " "); } }
接下来便是BST的插入和搜索。
public class BST { /** * <p>name: main</p> * <p>description: </p> * <p>return: void</p> */ public static void main(String[] args) { // TODO Auto-generated method stub // 依次将数组中的元素插入,默认没有重复数据 int[] array = { 4, 2, 1, 0, 3, 5, 9, 7, 6, 8 }; // 创建根节点; Node root = new Node(array[0]); for (int i = 1; i < array.length; i++) { insert(root, array[i]); } TreeUtils.fir(root); System.out.println(""); TreeUtils.mid(root); System.out.println(""); TreeUtils.las(root); } /** * <p> * name: insert * </p> * <p> * description: (递归)插入,也就是创建。一共才16行代码,切记切记 * </p> * <p> * return: void * </p> */ public static void insert(Node node,int data){ int key = node.data; if (key > data) { if (node.left == null) { node.left = new Node(data); } else { insert(node.left, data); } } else if (key < data) { if (node.right == null) { node.right = new Node(data); } else { insert(node.right, data); } } } /** * <p> * name: search * </p> * <p> * description: (递归)搜索。与插入的思路基本一样,一共才13行代码,切记切记 * </p> * <p> * return: boolean * </p> */ public static boolean search(Node node, int data) { if (node != null) { int key = node.data; if (key == data) { return true; } else if (key > data) { return search(node.left, data); } else if (key < data) { return search(node.right, data); } } return false; } }
1 0
- 算法--查找--二叉排序树创建、查找
- 查找算法之二叉排序树查找
- 二叉排序树创建、查找、删除
- 查找算法----二叉排序树
- [转载]查找算法----二叉排序树
- 二叉排序树 查找算法 java
- 查找算法之二叉排序树
- 二叉排序树之查找算法
- 二叉排序树的创建和查找
- 二叉排序树的创建与查找
- 二叉排序树(创建,查找,删除)
- 查找算法(基于二叉排序树的查找)
- 查找算法三之二叉排序树
- Java查找算法(四): 二叉排序树
- 查找算法,简单查找,二叉排序树,索引查找,哈希表
- 二叉排序树查找
- 二叉排序树查找
- 查找、二叉排序树
- Keil系列教程(汇总)
- 文章标题
- PPT流程文字转变为美观图形
- [SIM] The maximum transfer rate between "UE" and "SIM card"
- listview常用的事件:点击,滑动
- 算法--查找--二叉排序树创建、查找
- Unity3D:资源包的压缩(Asset Bundle Compression)
- 数据结构(C语言)-单向链表
- 【有奖内测】
- JAVA——Properties
- ViewHolder模式超简洁写法
- 【项目中】改变checkbox边框样式及颜色
- 完美长方体是不可能存在的 第五章
- nodejs Module did not self-register