转自:http://blog.csdn.net/lovesqcc/article/details/6246615

为了克服对树结构编程的恐惧感,决心自己实现一遍二叉查找树,以便掌握关于树结构编程的一些技巧和方法。以下是基本思路:

[1] 关于容器与封装。封装,是一种非常重要的系统设计思想;无论是面向过程的函数,还是面向对象的对象,都是实现抽象和封装的技术手段。要使系统更加安全更具可维护性,就应当将封装思想谨记心中。容器是封装思想的绝好示例。用户对容器的印象应该简洁地表达为:A. 可以存入指定的东西; B. 可以取出所期望的东西。 而至于这容器中究竟有什么机关,藏的是毒蛇还是黄金,都是对用户不可见的。二叉查找树就是这样一个容器。面向对象编程中,为实现树结构,自然要对树结点对象进行建模。这里采用了内部类;外部类对二叉查找树进行建模,而树结点作为内部类实现。

[2] 本程序尽量实现一个比较实用的二叉查找树,其中包括动态的插入、删除操作;查询给定关键字、最小关键字、最大关键字;获取二叉树的有序列表(用于排序)等。因为我希望以后还能用到这个容器的,而不仅仅是编程练习。二叉查找树操作的大部分算法参考了《算法导论2》第12章内容,删除操作略显笨拙。程序中有错误之处,欢迎指出。

[3]  程序如下:

[c-sharp] view plaincopyprint?
  1. /**
  2. * @author shuqin1984  2011-3-13
  3. *
  4. * 此程序实现一个二叉查找树的功能,可以进行动态插入、删除关键字;
  5. * 查询给定关键字、最小关键字、最大关键字;转换为有序列表(用于排序)
  6. *
  7. *
  8. */
  9. package datastructure.tree;
  10. import java.util.ArrayList;
  11. import java.util.List;
  12. public class BinarySearchTree {
  13. // 树的根结点
  14. private TreeNode root = null;
  15. // 遍历结点列表
  16. private List<TreeNode> nodelist = new ArrayList<TreeNode>();
  17. private class TreeNode {
  18. private int key;
  19. private TreeNode leftChild;
  20. private TreeNode rightChild;
  21. private TreeNode parent;
  22. public TreeNode(int key, TreeNode leftChild, TreeNode rightChild, TreeNode parent) {
  23. this.key = key;
  24. this.leftChild = leftChild;
  25. this.rightChild = rightChild;
  26. this.parent = parent;
  27. }
  28. public int getKey() {
  29. return key;
  30. }
  31. public String toString()
  32. {
  33. String leftkey = (leftChild == null ? "" : String.valueOf(leftChild.key));
  34. String rightkey = (rightChild == null ? "" : String.valueOf(rightChild.key));
  35. return "(" + leftkey + " , " + key + " , " + rightkey + ")";
  36. }
  37. }
  38. /**
  39. * isEmpty: 判断二叉查找树是否为空;若为空,返回 true ,否则返回 false .
  40. *
  41. */
  42. public boolean isEmpty()
  43. {
  44. if (root == null) {
  45. return true;
  46. } else {
  47. return false;
  48. }
  49. }
  50. /**
  51. * TreeEmpty: 对于某些二叉查找树操作(比如删除关键字)来说,若树为空,则抛出异常。
  52. */
  53. public void TreeEmpty() throws Exception
  54. {
  55. if (isEmpty()) {
  56. throw new Exception("树为空!");
  57. }
  58. }
  59. /**
  60. * search: 在二叉查找树中查询给定关键字
  61. * @param key 给定关键字
  62. * @return 匹配给定关键字的树结点
  63. */
  64. public TreeNode search(int key)
  65. {
  66. TreeNode pNode = root;
  67. while (pNode != null && pNode.key != key) {
  68. if (key < pNode.key) {
  69. pNode = pNode.leftChild;
  70. }
  71. else {
  72. pNode = pNode.rightChild;
  73. }
  74. }
  75. return pNode;
  76. }
  77. /**
  78. * minElemNode: 获取二叉查找树中的最小关键字结点
  79. * @return 二叉查找树的最小关键字结点
  80. * @throws Exception 若树为空,则抛出异常
  81. */
  82. public TreeNode minElemNode(TreeNode node) throws Exception
  83. {
  84. if (node == null) {
  85. throw new Exception("树为空!");
  86. }
  87. TreeNode pNode = node;
  88. while (pNode.leftChild != null) {
  89. pNode = pNode.leftChild;
  90. }
  91. return pNode;
  92. }
  93. /**
  94. * maxElemNode: 获取二叉查找树中的最大关键字结点
  95. * @return 二叉查找树的最大关键字结点
  96. * @throws Exception 若树为空,则抛出异常
  97. */
  98. public TreeNode maxElemNode(TreeNode node) throws Exception
  99. {
  100. if (node == null) {
  101. throw new Exception("树为空!");
  102. }
  103. TreeNode pNode = node;
  104. while (pNode.rightChild != null) {
  105. pNode = pNode.rightChild;
  106. }
  107. return pNode;
  108. }
  109. /**
  110. * successor: 获取给定结点在中序遍历顺序下的后继结点
  111. * @param node 给定树中的结点
  112. * @return 若该结点存在中序遍历顺序下的后继结点,则返回其后继结点;否则返回 null
  113. * @throws Exception
  114. */
  115. public TreeNode successor(TreeNode node) throws Exception
  116. {
  117. if (node == null) {
  118. return null;
  119. }
  120. // 若该结点的右子树不为空,则其后继结点就是右子树中的最小关键字结点
  121. if (node.rightChild != null) {
  122. return minElemNode(node.rightChild);
  123. }
  124. // 若该结点右子树为空
  125. TreeNode parentNode = node.parent;
  126. while (parentNode != null && node == parentNode.rightChild) {
  127. node = parentNode;
  128. parentNode = parentNode.parent;
  129. }
  130. return parentNode;
  131. }
  132. /**
  133. * precessor: 获取给定结点在中序遍历顺序下的前趋结点
  134. * @param node 给定树中的结点
  135. * @return 若该结点存在中序遍历顺序下的前趋结点,则返回其前趋结点;否则返回 null
  136. * @throws Exception
  137. */
  138. public TreeNode precessor(TreeNode node) throws Exception
  139. {
  140. if (node == null) {
  141. return null;
  142. }
  143. // 若该结点的左子树不为空,则其前趋结点就是左子树中的最大关键字结点
  144. if (node.leftChild != null) {
  145. return maxElemNode(node.leftChild);
  146. }
  147. // 若该结点左子树为空
  148. TreeNode parentNode = node.parent;
  149. while (parentNode != null && node == parentNode.leftChild) {
  150. node = parentNode;
  151. parentNode = parentNode.parent;
  152. }
  153. return parentNode;
  154. }
  155. /**
  156. * insert: 将给定关键字插入到二叉查找树中
  157. * @param key 给定关键字
  158. */
  159. public void insert(int key)
  160. {
  161. TreeNode parentNode = null;
  162. TreeNode newNode = new TreeNode(key, null, null,null);
  163. TreeNode pNode = root;
  164. if (root == null) {
  165. root = newNode;
  166. return ;
  167. }
  168. while (pNode != null) {
  169. parentNode = pNode;
  170. if (key < pNode.key) {
  171. pNode = pNode.leftChild;
  172. }
  173. else if (key > pNode.key) {
  174. pNode = pNode.rightChild;
  175. } else {
  176. // 树中已存在匹配给定关键字的结点,则什么都不做直接返回
  177. return ;
  178. }
  179. }
  180. if (key < parentNode.key) {
  181. parentNode.leftChild = newNode;
  182. newNode.parent = parentNode;
  183. }
  184. else {
  185. parentNode.rightChild = newNode;
  186. newNode.parent = parentNode;
  187. }
  188. }
  189. /**
  190. * insert: 从二叉查找树中删除匹配给定关键字相应的树结点
  191. * @param key 给定关键字
  192. */
  193. public void delete(int key) throws Exception
  194. {
  195. TreeNode pNode = search(key);
  196. if (pNode == null) {
  197. throw new Exception("树中不存在要删除的关键字!");
  198. }
  199. delete(pNode);
  200. }
  201. /**
  202. * delete: 从二叉查找树中删除给定的结点.
  203. * @param pNode 要删除的结点
  204. *
  205. * 前置条件: 给定结点在二叉查找树中已经存在
  206. * @throws Exception
  207. */
  208. private void delete(TreeNode pNode) throws Exception
  209. {
  210. if (pNode == null) {
  211. return ;
  212. }
  213. if (pNode.leftChild == null && pNode.rightChild == null) { // 该结点既无左孩子结点,也无右孩子结点
  214. TreeNode parentNode = pNode.parent;
  215. if (pNode == parentNode.leftChild) {
  216. parentNode.leftChild = null;
  217. } else {
  218. parentNode.rightChild = null;
  219. }
  220. return ;
  221. }
  222. if (pNode.leftChild == null && pNode.rightChild != null) { // 该结点左孩子结点为空,右孩子结点非空
  223. TreeNode parentNode = pNode.parent;
  224. if (pNode == parentNode.leftChild) {
  225. parentNode.leftChild = pNode.rightChild;
  226. pNode.rightChild.parent = parentNode;
  227. }
  228. else {
  229. parentNode.rightChild = pNode.rightChild;
  230. pNode.rightChild.parent = parentNode;
  231. }
  232. return ;
  233. }
  234. if (pNode.leftChild != null && pNode.rightChild == null) { // 该结点左孩子结点非空,右孩子结点为空
  235. TreeNode parentNode = pNode.parent;
  236. if (pNode == parentNode.leftChild) {
  237. parentNode.leftChild = pNode.leftChild;
  238. pNode.rightChild.parent = parentNode;
  239. }
  240. else {
  241. parentNode.rightChild = pNode.leftChild;
  242. pNode.rightChild.parent = parentNode;
  243. }
  244. return ;
  245. }
  246. // 该结点左右孩子结点均非空,则删除该结点的后继结点,并用该后继结点取代该结点
  247. TreeNode successorNode = successor(pNode);
  248. delete(successorNode);
  249. pNode.key = successorNode.key;
  250. }
  251. /**
  252. * inOrderTraverseList: 获得二叉查找树的中序遍历结点列表
  253. * @return 二叉查找树的中序遍历结点列表
  254. */
  255. public List<TreeNode> inOrderTraverseList()
  256. {
  257. if (nodelist != null) {
  258. nodelist.clear();
  259. }
  260. inOrderTraverse(root);
  261. return nodelist;
  262. }
  263. /**
  264. * inOrderTraverse: 对给定二叉查找树进行中序遍历
  265. * @param root 给定二叉查找树的根结点
  266. */
  267. private void inOrderTraverse(TreeNode root)
  268. {
  269. if (root != null) {
  270. inOrderTraverse(root.leftChild);
  271. nodelist.add(root);
  272. inOrderTraverse(root.rightChild);
  273. }
  274. }
  275. /**
  276. * toStringOfOrderList: 获取二叉查找树中关键字的有序列表
  277. * @return 二叉查找树中关键字的有序列表
  278. */
  279. public String toStringOfOrderList()
  280. {
  281. StringBuilder sbBuilder = new StringBuilder(" [ ");
  282. for (TreeNode p: inOrderTraverseList()) {
  283. sbBuilder.append(p.key);
  284. sbBuilder.append(" ");
  285. }
  286. sbBuilder.append("]");
  287. return sbBuilder.toString();
  288. }
  289. /**
  290. * 获取该二叉查找树的字符串表示
  291. */
  292. public String toString()
  293. {
  294. StringBuilder sbBuilder = new StringBuilder(" [ ");
  295. for (TreeNode p: inOrderTraverseList()) {
  296. sbBuilder.append(p);
  297. sbBuilder.append(" ");
  298. }
  299. sbBuilder.append("]");
  300. return sbBuilder.toString();
  301. }
  302. public TreeNode getRoot() {
  303. return root;
  304. }
  305. public static void testNode(BinarySearchTree bst, TreeNode pNode) throws Exception {
  306. System.out.println("本结点: " + pNode);
  307. System.out.println("前趋结点: " + bst.precessor(pNode));
  308. System.out.println("后继结点: " + bst.successor(pNode));
  309. }
  310. public static void testTraverse(BinarySearchTree bst) {
  311. System.out.println("二叉树遍历:" + bst);
  312. System.out.println("二叉查找树转换为有序列表: " + bst.toStringOfOrderList());
  313. }
  314. public static void main(String[] args)
  315. {
  316. try {
  317. BinarySearchTree bst = new BinarySearchTree();
  318. System.out.println("查找树是否为空? " + (bst.isEmpty() ? "是" : "否"));
  319. int[] keys = new int[] {15, 6, 18, 3, 7, 13, 20, 2, 9, 4};
  320. for (int key: keys) {
  321. bst.insert(key);
  322. }
  323. System.out.println("查找树是否为空? " + (bst.isEmpty() ? "是" : "否"));
  324. TreeNode minkeyNode = bst.minElemNode(bst.getRoot());
  325. System.out.println("最小关键字: " + minkeyNode.getKey());
  326. testNode(bst, minkeyNode);
  327. TreeNode maxKeyNode = bst.maxElemNode(bst.getRoot());
  328. System.out.println("最大关键字: " + maxKeyNode.getKey());
  329. testNode(bst, maxKeyNode);
  330. System.out.println("根结点关键字: " + bst.getRoot().getKey());
  331. testNode(bst, bst.getRoot());
  332. testTraverse(bst);
  333. System.out.println("****************************** ");
  334. System.out.println("查找 7 : " + (bst.search(7) != null ? "查找成功!" : "查找失败,不存在该关键字!"));
  335. bst.delete(7);
  336. System.out.println("查找 7 : " + (bst.search(7) != null ? "查找成功!" : "查找失败,不存在该关键字!"));
  337. System.out.println("查找 12 : " + (bst.search(12) != null ? "查找成功!" : "查找失败,不存在该关键字!"));
  338. bst.insert(12);
  339. System.out.println("查找 12 : " + (bst.search(12) != null ? "查找成功!" : "查找失败,不存在该关键字!"));
  340. testTraverse(bst);
  341. System.out.println("****************************** ");
  342. bst.insert(16);
  343. bst.delete(6);
  344. bst.delete(4);
  345. testTraverse(bst);
  346. } catch (Exception e) {
  347. System.out.println(e.getMessage());
  348. e.printStackTrace();
  349. }
  350. }
  351. }

转载于:https://www.cnblogs.com/cugwx/p/3664306.html

二叉查找树的Java实现相关推荐

  1. 二叉查找树之 Java的实现

    参考:http://www.cnblogs.com/skywang12345/p/3576452.html 二叉查找树简介 二叉查找树(Binary Search Tree),又被称为二叉搜索树. 它 ...

  2. 数据结构与算法-二叉查找树(java描述)

    一.概述 二叉排序树(Binary Sort Tree)又称二叉查找树(Binary Search Tree),亦称二叉搜索树. 1.1.定义 二叉排序树或者是一棵空树,或者是具有下列性质的二叉树: ...

  3. xdocument查找节点值_二叉查找树(java)

    一棵二叉查找树(BST)是一颗二叉树,其中每个节点都含有一个Comparable的键且每个节点的键(以及相关的值)都大于其左子树中的任意节点的键而小于右子树的任意结点的键. 数据表示 和链表一样,我们 ...

  4. 二叉搜索树 java_二叉查找树之 Java的实现【下】

    /** * Java 语言: 二叉查找树 * * @author skywang * @date 2013/11/07 */ public class BSTree>{ private BSTN ...

  5. 【数据结构与算法】二叉查找树的Java实现

    二叉查找树(二叉排序树) 二叉排序树(二叉查找树)(一种动态查找数据结构) 二叉排序树又称二叉查找树,它或是一棵空的二叉树,或是一棵具有下列性质的二叉树: 若它的左子树不空,则左子树上左右结点的值均小 ...

  6. 构造avl树_图解 AVL 自平衡二叉查找树及 java 实现

    思维导图 AVL树 AVL树是根据它的发明者G.M. Adelson-Velsky和E.M. Landis命名的. 它是最先发明的自平衡二叉查找树(Self-balancing binary sear ...

  7. 数据结构笔记--二叉查找树概述以及java代码实现

    一些概念: 二叉查找树的重要性质:对于树中的每一个节点X,它的左子树任一节点的值均小于X,右子树上任意节点的值均大于X. 二叉查找树是java的TreeSet和TreeMap类实现的基础. 由于树的递 ...

  8. Java数据结构与算法:二叉树

    原文链接:http://www.cnblogs.com/skywang12345/p/3576452.html 1. 二叉查找树简介 二叉查找树(Binary Search Tree),又被称为二叉搜 ...

  9. java代码 计算器_java代码---------计算器实现

    总结:虽然,没有人会帮你到底,凭什么要对你怜香惜玉 注意实现哪一个运算就把相关代码放在else if这个判断语句里面 package com.rue; import java.awt.BorderLa ...

最新文章

  1. 遇到网络问题你是怎么解决的?安琪拉有二招
  2. 死而复生?RethinkDB宣布进入Linux基金会!
  3. Coursera-AndrewNg(吴恩达)机器学习笔记——第四周编程作业(多分类与神经网络)...
  4. 定时任务的并发_03
  5. 判断五个分数等级划分_压力表精度等级怎么算?压力表精度等级划分及检验项目...
  6. 函数或变量 rtenslearn_c 无法识别_深度学习的数学-卷积神经网络的结构和变量关系...
  7. JS 逻辑中断(二)
  8. sm缩写代表什么意思_PE给水管常见的字母缩写都代表什么?
  9. 谈内置创新5.1/7.1声卡效果开混响模式滋滋啦啦炸麦声音【案例解析】
  10. Excel表格合并单元格丢失边框
  11. 联想拯救者Y7000关闭触摸板
  12. 修改微信聊天记录保存位置
  13. 人在年轻的时候,最核心的能力是什么?-复利(转自知乎)
  14. python客户价值分析_Python实现RFM客户价值分析
  15. WIN10安装cad2006提示无权限安装的解决办法
  16. SCAU程序设计在线实训平台_实验_数据结构_实验4
  17. wind(万得)资讯金融终端登录失败问题
  18. 数字图像处理实验——图片压缩与解压(opencv)
  19. C 语言回调函数详解
  20. 对外经济贸易大学继续教育学院国际贸易实务模拟实习项目启动

热门文章

  1. JVM 调优实战--什么是调优及如何调优的思路
  2. Dubbo 注解驱动(Annotation-Driven)
  3. access窗体中再制作查询窗体_Access
  4. centos 7.9 scp命令 实现远程拷贝文件
  5. QML 性能优化建议(一)
  6. 用paddleocr识别汉字_汉字设计中的度量标准(三)
  7. java jsp生成pdf_如何使用jsp、servlet输出iText生成的pdf
  8. JVM运行时结构、Java内存管理、JVM实例、HotSpot VM对象的创建、内存布局和访问定位
  9. android 5.0 ios 8,Android 5.0和iOS8.1哪个好?安卓5.0与iOS8.1区别对比
  10. C++ 重载机制实现原理