二叉树 BinaryTree (先序、中序、后序遍历 节点查找、插入、删除 完整类) Java数据结构与算法

源代码:

view plain
  1. /**
  2. *
  3. * @author sunnyykn
  4. */
  5. import java.io.*;
  6. import java.util.*;
  7. class Node
  8. {
  9. public int iData;       //data item (key)
  10. public double dData;    //data item
  11. public Node leftChild;  //this node's left child
  12. public Node rightChild; //this node's right child
  13. public void displayNode()   //display ourself
  14. {
  15. System.out.print("{");
  16. System.out.print(iData);
  17. System.out.print(",");
  18. System.out.print(dData);
  19. System.out.print("}");
  20. }
  21. }//end class Node
  22. class Tree
  23. {
  24. private Node root;      //first node of tree
  25. public Tree()
  26. {
  27. root = null;        //no nodes in tree yet
  28. }
  29. public Node find(int key)   //find node with given key
  30. {
  31. Node current = root;        //start at root
  32. while(current.iData != key) //while no match
  33. {
  34. if(key < current.iData) //go left?
  35. current = current.leftChild;
  36. else                    //go right?
  37. current = current.rightChild;
  38. if (current == null)    //didn't find it
  39. return null;
  40. }
  41. return current;
  42. }//end find()
  43. public void insert(int id ,double dd)
  44. {
  45. Node newNode = new Node();      //make new node
  46. newNode.iData = id;             //insert data
  47. newNode.dData = dd;
  48. if( root == null )              //no node in root
  49. root = newNode;
  50. else
  51. {
  52. Node current = root;        //start at root
  53. Node parent;
  54. while( true )
  55. {
  56. parent = current;
  57. if(id < current.iData)  //go left?
  58. {
  59. current = current.leftChild;
  60. if(current == null)  //if end of the line
  61. {
  62. parent.leftChild = newNode;
  63. return ;
  64. }
  65. }//end if go left
  66. else                    //or go right
  67. {
  68. current = current.rightChild;
  69. if(current == null) //if end of the line
  70. {
  71. parent.rightChild = newNode;
  72. return ;
  73. }
  74. }//end else go right
  75. }//end while
  76. }//end else not root
  77. }//end insert()
  78. public boolean delete(int key)      //delete node with given key
  79. {
  80. Node current = root;
  81. Node parent = root;
  82. boolean isLeftChild = true;
  83. while(current.iData != key)
  84. {
  85. parent = current;
  86. if(key < current.iData)
  87. {
  88. isLeftChild = true;
  89. current = current.leftChild;
  90. }
  91. else
  92. {
  93. isLeftChild = false;
  94. current = current.rightChild;
  95. }
  96. if(current == null)
  97. return false;
  98. }//end while
  99. //found node to delete
  100. //if no children , simply delete it
  101. if(current.leftChild == null && current.rightChild == null)
  102. {
  103. if (current == root)
  104. root = null;
  105. else if(isLeftChild)
  106. parent.leftChild = null;
  107. else
  108. parent.rightChild = null;
  109. }
  110. //if no right child , replace with left subtree
  111. else if(current.rightChild == null)
  112. {
  113. if (current == root)
  114. root = current.leftChild;
  115. else if (isLeftChild)
  116. parent.leftChild = current.leftChild;
  117. else
  118. parent.rightChild = current.leftChild;
  119. }
  120. //if no left child , replace with right subtree
  121. else if (current.leftChild == null)
  122. {
  123. if (current == root)
  124. root = current.rightChild;
  125. else if(isLeftChild)
  126. parent.leftChild = current.rightChild;
  127. else
  128. parent.rightChild = current.rightChild;
  129. }
  130. //two children,so replace with inorder successor
  131. else
  132. {
  133. //get successor of node to delete(current)
  134. Node successor = getSuccessor(current);
  135. //connect parent of current to successor insteed
  136. if(current == root)
  137. root = successor;
  138. else if (isLeftChild)
  139. parent.leftChild = successor;
  140. else
  141. parent.rightChild = successor;
  142. //connect successor to current's left child
  143. successor.leftChild = current.leftChild;
  144. }//end else two children
  145. //(successor cannot have a left child)
  146. return true;
  147. }//end delete()
  148. //return node with next-highest value after delNode
  149. //goes to right child , then right child's left descendents
  150. private Node getSuccessor(Node delNode)
  151. {
  152. Node successorParent = delNode;
  153. Node successor = delNode;
  154. Node current = delNode.rightChild;      //go to right child
  155. while(current != null)                  //until no more left children
  156. {
  157. successorParent = successor;
  158. successor = current;
  159. current = current.leftChild;        //go to left child
  160. }
  161. if (successor != delNode.rightChild)    //if successor not right child , make connections
  162. {
  163. successorParent.leftChild = successor.rightChild;
  164. successor.rightChild = delNode.rightChild;
  165. }
  166. return successor;
  167. }
  168. public void traverse(int traverseType)
  169. {
  170. switch(traverseType)
  171. {
  172. case 1:
  173. System.out.print("/nPreorder traversal:");
  174. preOrder(root);
  175. break;
  176. case 2:
  177. System.out.print("/nInorder traversal: ");
  178. inOrder(root);
  179. break;
  180. case 3:
  181. System.out.print("/nPostorder traversal:");
  182. postOrder(root);
  183. break;
  184. }
  185. System.out.println("");
  186. }
  187. private void preOrder(Node localRoot)
  188. {
  189. if (localRoot != null)
  190. {
  191. System.out.print(localRoot.iData + " ");
  192. preOrder(localRoot.leftChild);
  193. preOrder(localRoot.rightChild);
  194. }
  195. }
  196. private void inOrder(Node localRoot)
  197. {
  198. if(localRoot != null)
  199. {
  200. inOrder(localRoot.leftChild);
  201. System.out.print(localRoot.iData + " ");
  202. inOrder(localRoot.rightChild);
  203. }
  204. }
  205. private void postOrder(Node localRoot)
  206. {
  207. if (localRoot != null)
  208. {
  209. postOrder(localRoot.leftChild);
  210. postOrder(localRoot.rightChild);
  211. System.out.print(localRoot.iData + " ");
  212. }
  213. }
  214. public void displayTree()
  215. {
  216. Stack globalStack = new Stack();
  217. globalStack.push(root);
  218. int nBlanks = 32;
  219. boolean isRowEmpty = false ;
  220. System.out.println("....................................................");
  221. while(isRowEmpty == false)
  222. {
  223. Stack localStack = new Stack();
  224. isRowEmpty = true;
  225. for(int j = 0;j < nBlanks; j ++)
  226. System.out.print(" ");
  227. while(globalStack.isEmpty() == false)
  228. {
  229. Node temp = (Node)globalStack.pop();
  230. if(temp != null)
  231. {
  232. System.out.print(temp.iData);
  233. localStack.push(temp.leftChild);
  234. localStack.push(temp.rightChild);
  235. if(temp.leftChild != null || temp.rightChild != null)
  236. isRowEmpty = false;
  237. }
  238. else
  239. {
  240. System.out.print("--");
  241. localStack.push(null);
  242. localStack.push(null);
  243. }
  244. for(int j = 0; j < nBlanks*2 - 2;j ++)
  245. System.out.print(" ");
  246. }//end while globalStack not empty
  247. System.out.println("");
  248. nBlanks /= 2;
  249. while(localStack.isEmpty() == false)
  250. globalStack.push( localStack.pop() );
  251. }//end while isRowEmpty is false
  252. System.out.println("....................................................");
  253. }//end displayTree()
  254. }//end class Tree
  255. class TreeApp
  256. {
  257. public static void main(String[] args) throws IOException
  258. {
  259. int value ;
  260. Tree theTree = new Tree();
  261. theTree.insert(50, 1.5);
  262. theTree.insert(25, 1.2);
  263. theTree.insert(75, 1.7);
  264. theTree.insert(12, 1.5);
  265. theTree.insert(37, 1.2);
  266. theTree.insert(43, 1.7);
  267. theTree.insert(30, 1.5);
  268. theTree.insert(33, 1.2);
  269. theTree.insert(87, 1.7);
  270. theTree.insert(93, 1.5);
  271. theTree.insert(97, 1.5);
  272. while( true )
  273. {
  274. System.out.print("Enter first letter of show,insert,find,delete,or traverse:");
  275. int choice = getChar();
  276. switch( choice )
  277. {
  278. case 's':
  279. theTree.displayTree();
  280. break;
  281. case 'i':
  282. System.out.print("Enter value to insert:");
  283. value = getInt();
  284. theTree.insert(value, value + 0.9);
  285. break;
  286. case 'f':
  287. System.out.print("Enter value to find:");
  288. value = getInt();
  289. Node found = theTree.find(value);
  290. if(found != null)
  291. {
  292. System.out.print("Found:");
  293. found.displayNode();
  294. System.out.print("/n");
  295. }
  296. else
  297. {
  298. System.out.print("Could not find ");
  299. System.out.print(value + '/n');
  300. }
  301. break;
  302. case 'd':
  303. System.out.print("Enter value to delete:");
  304. value = getInt();
  305. boolean didDelete = theTree.delete(value);
  306. if(didDelete)
  307. System.out.print("Deleted " + value + '/n');
  308. else{
  309. System.out.print("Could not delete ");
  310. System.out.print(value + '/n');
  311. }
  312. break;
  313. case 't':
  314. System.out.print("Enter type 1,2 or 3:");
  315. value = getInt();
  316. theTree.traverse(value);
  317. break;
  318. default:
  319. System.out.print("Invalid entry/n");
  320. }//end switch
  321. }//end while
  322. }//end main()
  323. public static String getString() throws IOException
  324. {
  325. InputStreamReader isr = new InputStreamReader(System.in);
  326. BufferedReader br = new BufferedReader(isr);
  327. String s = br.readLine();
  328. return s;
  329. }
  330. public static char getChar() throws IOException
  331. {
  332. String s = getString();
  333. return s.charAt(0);
  334. }
  335. public static int getInt() throws IOException
  336. {
  337. String s = getString();
  338. return Integer.parseInt(s);
  339. }
  340. }//end class TreeApp

二叉树 BinaryTree (先序、中序、后序遍历 节点查找、插入、删除 完整类) Java数据结构与算法相关推荐

  1. 二叉树的前、中、后序遍历的代码实现(递归方式)

    测试的二叉树的结构 root lfb1 rtb1rtb2 控制台输出的遍历结果 ======从根节点开始,前序遍历此二叉树======= root lfb1 rtb1 rtb2 ======从根节点开 ...

  2. 二叉树的前、中、后序遍历

    所谓二叉树遍历是按某种特定规则,依次对二叉树中的节点进行相应的操作,并且每个节点只操作一次.访问结点所做的操作依赖于具体的应用问题. 遍历是二叉树上最重要的运算之一,也是二叉树进行其它运算的基础. 二 ...

  3. 【数据结构与算法】力扣:二叉树的前、中、后序遍历

    递归法 前序遍历 给你二叉树的根节点 root ,返回它节点值的前序 遍历. 示例 1: 输入:root = [1,null,2,3] 输出:[1,2,3] 示例 2: 输入:root = [] 输出 ...

  4. java中二叉树_Java工程师面试1000题224-递归非递归实现二叉树前、中、后序遍历...

    224.使用递归和非递归实现二叉树的前.中.后序遍历 使用递归来实现二叉树的前.中.后序遍历比较简单,直接给出代码,我们重点讨论非递归的实现. class Node { public int valu ...

  5. 二叉树遍历方法——前、中、后序遍历(图解)

    目录 一.前序遍历 (1)递归版本 (2)非递归版本 二.中序遍历 (1)递归版本 (2)非递归版本 三.后序遍历 (1)递归版本 (2)非递归版本 四.总结 五.测试程序 六.程序输出 二叉树的遍历 ...

  6. 二叉树的前、中、后的非递归遍历

    题目 实现一个链式存储的二叉树,采用非递归的形式,按照前.中.后序的顺序遍历二叉树. 代码 /** * 二叉树的前.中.后序的非递归遍历 **/#include <iostream> us ...

  7. 先序序列和中序序列构造二叉树,中序序列和后序序列构造二叉树

    1:首先读者要了解二叉树BinaryTree基本概念,其次区分左子树与左孩子节点,右子树与右孩子节点.(在数据结构中      一个节点可以成为一棵树,对于没有孩子节点的节点称为为叶子节点). 2:在 ...

  8. 已知一棵二叉树的中序序列和后序序列,写一个建立该二叉树的二叉链表存储结构的算法...

    已知一棵二叉树的中序序列和后序序列,写一个建立该二叉树的二叉链表存储结构的算法 #define N 10 //二叉树节点的个数 char postorderstr[]={};//后序序列 char i ...

  9. 7-10 先序序列创建二叉树,输出先序序列、中序序列、后序序列并输出叶子结点数 (10 分)

    7-10 先序序列创建二叉树,输出先序序列.中序序列.后序序列并输出叶子结点数 (10 分) 对于给定的二叉树,输出其先序序列.中序序列.后序序列并输出叶子结点数. 输入格式: 二叉树的先序遍历序列. ...

最新文章

  1. android ffmpeg 编码h264,Mac系统下ffmpeg+h264+flv编码的android录制屏幕实现2
  2. Sinew Ex深度发掘金融衍生品市场价值
  3. elementui table html,elementUI Table表格表头自定义
  4. window.onload 不执行
  5. 在linux系统下安装两个nginx以及启动、停止、重起
  6. 编译linux内核成vmlinuz,编译一个内核 - no bzImage/vmlinuz生成
  7. 16行代码AC_【第十届蓝桥杯省赛c/c++B组真题解析】7.完全二叉树的权值
  8. different behavior dialog popup display no
  9. 如何批量查询PR值、百度权重、百度快照及收录量,用BlueCatTools批量网站查询工具
  10. Java之WeakReference与SoftReference使用讲解
  11. mysql按照列构建索引_列存储索引增强功能–在线和离线(重新)构建
  12. 单片机c语言程序包txt,单片机C语言应用100例(第3版)(含光盘1张) pdf epub mobi txt 下载...
  13. 悼念前端大牛司徒正美
  14. Android限制录制屏幕无声音,哪一个安卓录屏软件可以录制系统的声音
  15. 如何最大效率压缩视频文件(ffmpeg)
  16. 阿里电商故障治理和故障演练实践
  17. 【托业】【跨栏】TEST04
  18. 设备管理器中的非即插即用驱动程序
  19. cass实体编码列表
  20. hdu1404 博弈

热门文章

  1. 图像超分辨率(Super-Resolution)技术研究
  2. mysql为何不支持开窗函数?
  3. BZOJ1010:[HNOI2008]玩具装箱TOY(斜率优化DP)
  4. Java 学习笔记之 线程安全
  5. 原生js调用json方法
  6. ubuntu16.04安装zabbix-server3.4
  7. HDU - 6464 免费送气球(线段树二分)
  8. 51nod1363 最小公倍数之和
  9. python3----练习题(弹幕跟随)
  10. MYSQL第一章 创建表 修改表名 删除字段 添加字段 修改地段名