二叉查找树Java实现代码
二叉查找树(Binary Search Tree),或者是一颗空树,或者是具有下列性质的二叉树:
1、若它的左子树不空,则其左子树上的所有结点的值均小于它根结点的值;
2、若它的右子树不空,则其右子树上的所有结点的值均大于它根结点的值;
3、它的左、右子树也分别为二叉查找树。
实现代码如下:重点是理解插入和删除后树的重新调整
package cn.hm;/** * @author fjssharpsword 2016-7-20 * 实现一个二叉查找树的功能,可以进行动态插入、删除关键字; * 查询给定关键字、最小关键字、最大关键字;转换为有序列表(用于排序) */ import java.util.ArrayList;
import java.util.List; public class BinarySearchTree { // 树的根结点 private TreeNode root = null; // 遍历结点列表 private List<TreeNode> nodelist = new ArrayList<TreeNode>(); //定义树结构private class TreeNode { private int key; private TreeNode leftChild; private TreeNode rightChild; private TreeNode parent; public TreeNode(int key, TreeNode leftChild, TreeNode rightChild, TreeNode parent) { this.key = key; this.leftChild = leftChild; this.rightChild = rightChild; this.parent = parent; } public int getKey() { return key; } public String toString() { String leftkey = (leftChild == null ? "" : String.valueOf(leftChild.key)); String rightkey = (rightChild == null ? "" : String .valueOf(rightChild.key)); return "(" + leftkey + " , " + key + " , " + rightkey + ")"; } } /** * isEmpty: 判断二叉查找树是否为空;若为空,返回 true ,否则返回 false . * */ public boolean isEmpty() { if (root == null) { return true; } else { return false; } } /** * TreeEmpty: 对于某些二叉查找树操作(比如删除关键字)来说,若树为空,则抛出异常。 */ public void TreeEmpty() throws Exception { if (isEmpty()) { throw new Exception("树为空!"); } } /** * search: 在二叉查找树中查询给定关键字 * * @param key 给定关键字 * @return 匹配给定关键字的树结点 */ public TreeNode search(int key) { TreeNode pNode = root; while (pNode != null && pNode.key != key) { if (key < pNode.key) { pNode = pNode.leftChild; } else { pNode = pNode.rightChild; } } return pNode; } /** * minElemNode: 获取二叉查找树中的最小关键字结点 * * @return 二叉查找树的最小关键字结点 ,一直向左* @throws Exception 若树为空,则抛出异常 */ public TreeNode minElemNode(TreeNode node) throws Exception { if (node == null) { throw new Exception("树为空!"); } TreeNode pNode = node; while (pNode.leftChild != null) { pNode = pNode.leftChild; } return pNode; } /** * maxElemNode: 获取二叉查找树中的最大关键字结点 * * @return 二叉查找树的最大关键字结点 ,一直向右* @throws Exception 若树为空,则抛出异常 */ public TreeNode maxElemNode(TreeNode node) throws Exception { if (node == null) { throw new Exception("树为空!"); } TreeNode pNode = node; while (pNode.rightChild != null) { pNode = pNode.rightChild; } return pNode; } /** * successor: 获取给定结点在中序遍历顺序下的后继结点 * @param node 给定树中的结点 * @return 若该结点存在中序遍历顺序下的后继结点,则返回其后继结点;否则返回 null * @throws Exception */ public TreeNode successor(TreeNode node) throws Exception { if (node == null) { return null; } // 若该结点的右子树不为空,则其后继结点就是右子树中的最小关键字结点 if (node.rightChild != null) { return minElemNode(node.rightChild); } // 若该结点右子树为空 TreeNode parentNode = node.parent; while (parentNode != null && node == parentNode.rightChild) { node = parentNode; parentNode = parentNode.parent; } return parentNode; } /** * precessor: 获取给定结点在中序遍历顺序下的前趋结点 * @param node 给定树中的结点 * @return 若该结点存在中序遍历顺序下的前趋结点,则返回其前趋结点;否则返回 null * @throws Exception */ public TreeNode precessor(TreeNode node) throws Exception { if (node == null) { return null; } // 若该结点的左子树不为空,则其前趋结点就是左子树中的最大关键字结点 if (node.leftChild != null) { return maxElemNode(node.leftChild); } // 若该结点左子树为空 TreeNode parentNode = node.parent; while (parentNode != null && node == parentNode.leftChild) { node = parentNode; parentNode = parentNode.parent; } return parentNode; } /** * insert: 将给定关键字插入到二叉查找树中 * 插入后要调整二叉查找树左小右大结构* @param key 给定关键字 */ public void insert(int key) { TreeNode parentNode = null; TreeNode newNode = new TreeNode(key, null, null, null); TreeNode pNode = root; if (root == null) { root = newNode; return; } while (pNode != null) { parentNode = pNode; if (key < pNode.key) { pNode = pNode.leftChild; } else if (key > pNode.key) { pNode = pNode.rightChild; } else { // 树中已存在匹配给定关键字的结点,则什么都不做直接返回 return; } } if (key < parentNode.key) { parentNode.leftChild = newNode; newNode.parent = parentNode; } else { parentNode.rightChild = newNode; newNode.parent = parentNode; } } /** * delete: 从二叉查找树中删除匹配给定关键字相应的树结点 * * @param key 给定关键字 */ public void delete(int key) throws Exception { TreeNode pNode = search(key); if (pNode == null) { throw new Exception("树中不存在要删除的关键字!"); } delete(pNode); } /** * delete: 从二叉查找树中删除给定的结点. * * @param pNode 要删除的结点 前置条件: 给定结点在二叉查找树中已经存在 * 删除后要调整二叉查找树,满足左小右大结构* @throws Exception */ private void delete(TreeNode pNode) throws Exception { if (pNode == null) { return; } if (pNode.leftChild == null && pNode.rightChild == null) { // 该结点既无左孩子结点,也无右孩子结点 TreeNode parentNode = pNode.parent; if (pNode == parentNode.leftChild) { parentNode.leftChild = null; } else { parentNode.rightChild = null; } pNode=null;return; } if (pNode.leftChild == null && pNode.rightChild != null) { // 该结点左孩子结点为空,右孩子结点非空 TreeNode parentNode = pNode.parent; TreeNode rightNode=pNode.rightChild;if (pNode == parentNode.leftChild) { rightNode.parent = parentNode; parentNode.leftChild = rightNode; } else { rightNode.parent = parentNode; parentNode.rightChild = rightNode; } pNode=null;return; } if (pNode.leftChild != null && pNode.rightChild == null) { // 该结点左孩子结点非空,右孩子结点为空 TreeNode parentNode = pNode.parent; TreeNode leftNode=pNode.leftChild;if (pNode == parentNode.leftChild) {leftNode.parent = parentNode;parentNode.leftChild = leftNode; } else { leftNode.parent = parentNode;parentNode.rightChild = leftNode; } pNode=null;return; } if(pNode.leftChild != null && pNode.rightChild != null){// 该结点左右孩子结点均非空TreeNode successorNode = successor(pNode); pNode.key = successorNode.key; delete(successorNode); }} /** * inOrderTraverseList: 获得二叉查找树的中序遍历结点列表 * * @return 二叉查找树的中序遍历结点列表 */ public List<TreeNode> inOrderTraverseList() { if (nodelist != null) { nodelist.clear(); } inOrderTraverse(root); return nodelist; } /** * inOrderTraverse: 对给定二叉查找树进行中序遍历 * * @param root 给定二叉查找树的根结点 */ private void inOrderTraverse(TreeNode root) { if (root != null) { inOrderTraverse(root.leftChild); nodelist.add(root); inOrderTraverse(root.rightChild); } } /** * toStringOfOrderList: 获取二叉查找树中关键字的有序列表 * * @return 二叉查找树中关键字的有序列表 */ public String toStringOfOrderList() { StringBuilder sbBuilder = new StringBuilder(" [ "); for (TreeNode p : inOrderTraverseList()) { sbBuilder.append(p.key); sbBuilder.append(" "); } sbBuilder.append("]"); return sbBuilder.toString(); } /** * 获取该二叉查找树的字符串表示 */ public String toString() { StringBuilder sbBuilder = new StringBuilder(" [ "); for (TreeNode p : inOrderTraverseList()) { sbBuilder.append(p.toString()); sbBuilder.append(" "); } sbBuilder.append("]"); return sbBuilder.toString(); } public TreeNode getRoot() { return root; } public static void testNode(BinarySearchTree bst, TreeNode pNode) throws Exception { System.out.println("本结点: " + pNode); System.out.println("前趋结点: " + bst.precessor(pNode)); System.out.println("后继结点: " + bst.successor(pNode)); } public static void testTraverse(BinarySearchTree bst) { System.out.println("二叉树遍历:" + bst.toString()); System.out.println("二叉查找树转换为有序列表: " + bst.toStringOfOrderList()); } public static void main(String[] args) { try { BinarySearchTree bst = new BinarySearchTree(); //插入System.out.println("查找树是否为空? " + (bst.isEmpty() ? "是" : "否")); int[] keys = new int[] { 52,18,69,32,10,2,7,72,86,98,100,5,1020,789,13,15 }; for (int key : keys) { bst.insert(key); } System.out.println("查找树是否为空? " + (bst.isEmpty() ? "是" : "否")); //找最小结点TreeNode minkeyNode = bst.minElemNode(bst.getRoot()); System.out.println("最小关键字: " + minkeyNode.getKey()); testNode(bst, minkeyNode); //找最大结点TreeNode maxKeyNode = bst.maxElemNode(bst.getRoot()); System.out.println("最大关键字: " + maxKeyNode.getKey()); testNode(bst, maxKeyNode); //根结点System.out.println("根结点关键字: " + bst.getRoot().getKey()); testNode(bst, bst.getRoot()); //遍历二叉树testTraverse(bst); //删除一个结点bst.delete(100); testTraverse(bst); } catch (Exception e) { System.out.println(e.getMessage()); e.printStackTrace(); } } }
执行结果如下:
查找树是否为空? 是
查找树是否为空? 否
最小关键字: 2
本结点: ( , 2 , 7)
前趋结点: null
后继结点: ( , 5 , )
最大关键字: 1020
本结点: (789 , 1020 , )
前趋结点: ( , 789 , )
后继结点: null
根结点关键字: 52
本结点: (18 , 52 , 69)
前趋结点: ( , 32 , )
后继结点: ( , 69 , 72)
二叉树遍历: [ ( , 2 , 7) ( , 5 , ) (5 , 7 , ) (2 , 10 , 13) ( , 13 , 15) ( , 15 , ) (10 , 18 , 32) ( , 32 , ) (18 , 52 , 69) ( , 69 , 72) ( , 72 , 86) ( , 86 , 98) ( , 98 , 100) ( , 100 , 1020) ( , 789 , ) (789 , 1020 , ) ]
二叉查找树转换为有序列表: [ 2 5 7 10 13 15 18 32 52 69 72 86 98 100 789 1020 ]
二叉树遍历: [ ( , 2 , 7) ( , 5 , ) (5 , 7 , ) (2 , 10 , 13) ( , 13 , 15) ( , 15 , ) (10 , 18 , 32) ( , 32 , ) (18 , 52 , 69) ( , 69 , 72) ( , 72 , 86) ( , 86 , 98) ( , 98 , 1020) ( , 789 , ) (789 , 1020 , ) ]
二叉查找树转换为有序列表: [ 2 5 7 10 13 15 18 32 52 69 72 86 98 789 1020 ]
二叉查找树Java实现代码相关推荐
- java编写代码用什么_如何学习用Java编写代码:为什么要学习以及从哪里开始
java编写代码用什么 by John Selawsky 约翰·塞劳斯基(John Selawsky) 如何学习用Java编写代码:为什么要学习以及从哪里开始 (How to learn to cod ...
- Java 常用代码汇总
欢迎关注方志朋的博客,回复"666"获面试宝典 1. 字符串有整型的相互转换 String a = String.valueOf(2); //integer to numeric ...
- 陌陌安全开源了 Java 静态代码安全审计插件
近日,陌陌安全开源了 Java 静态代码安全审计插件 MOMO Code Sec Inspector,侧重于在编码过程中发现项目潜在的安全风险,并提供一键修复能力. MOMO 安全团队认为,绝大部分 ...
- 《Java和Android开发实战详解》——2.5节良好的Java程序代码编写风格
本节书摘来自异步社区<Java和Android开发实战详解>一书中的第2章,第2.5节良好的Java程序代码编写风格,作者 陈会安,更多章节内容可以访问云栖社区"异步社区&quo ...
- 求一个简单的java线程代码,Java线程代码的实现方法
1.继承Thread 声明Thread的子类 运行thread子类的方法 2.创建Thread的匿名子类 3.实现Runnable接口 声明 运行 4.创建实现Runnable接口的匿名类 5.线程名 ...
- 你了解欧拉回路吗?(附Java实现代码)
文章目录 一:什么是欧拉回路? 二: 无向图中欧拉回路存在的条件 三:如何得到欧拉回路 四:Java实现 一:什么是欧拉回路? 不知道你有没有玩过这样一种叫"一笔画",从某一点开始 ...
- 哈夫曼编码(Huffman)Java实现代码
网上找到的一个组Huffman编码Java实现代码,比较经典. 1.主类,压缩和解压 package cn.hm;import java.io.BufferedInputStream; import ...
- java 定时器代码_Java定时器代码的编写
Java定时器代码的编写 在某些时候, 我们需要实现这样的`功能,某一程序隔一段时间执行一次,而这一事情由系统本身来完成,并不是人为的触发,我们一般可称此为定时器任务.其实到Java中,实现起来是非常 ...
- 经典KMP算法C++与Java实现代码
前言: KMP算法是一种字符串匹配算法,由Knuth,Morris和Pratt同时发现(简称KMP算法).KMP算法的关键是利用匹配失败后的信息,尽量减少模式串与主串的匹配次数以达到快速匹配的目的.比 ...
最新文章
- Objective-C Reflection(Objective-C 反射机制)实用随笔笔记(持续更新)
- system-copy 和 ShellExecute 用法
- 计算机信息处理技术知识点,计算机信息处理技术基础知识.doc
- 网站后台的lnmp启动与重启
- 【转】idea激活搭建授权服务器
- maven配置tomcat7
- 【飞秋】WF3.0和4.0区别介绍
- 翻译:Hystrix - How To Use
- 亲密关系沟通-【主动性】觉察自我的力量
- 【渝粤题库】陕西师范大学210007 幼儿园音乐教育 作业(高起专)
- 怎么撰写营销策划书?
- 你真的了解LinkedBlockingQueue的put,add和offer的区别吗
- Android 获取当前设备SIM运营商
- centos 禁止自动锁屏
- IOS gif图片播放 swift
- 基于Android Q 修改默认音量等级
- 算法设计与分析--昆虫繁殖
- 舆情监测系统工作流程大致是怎样的?
- 最常见的游戏建模软件有哪些?
- DAMA-第四章(数据架构)