在上一篇博客中,实现了Java中二叉树的四种遍历方式的递归实现,接下来,在此实现Java中非递归实现二叉树的前序、中序、后序、层序遍历,在非递归实现中,借助了栈来帮助实现遍历。前序和中序比较类似,也简单一些,但是后序遍历需要两个栈来进行辅助,稍微复杂一些,层序遍历中借助了一个队列来进行实现。

  同样是那棵二叉树

  • 前序遍历:4 2 1 3 6 5 7 8 10

  • 中序遍历:1 2 3 4 5 6 7 8 10

  • 后序遍历:1 3 2 5 10 8 7 6 4

  • 层序遍历:4 2 6 1 3 5 7 8 10

  1. import java.util.LinkedList;
  2. import java.util.Queue;
  3. import java.util.Stack;
  4. public class Tree<AnyType extends Comparable<? super AnyType>>
  5. {
  6. private static class BinaryNode<AnyType>
  7. {
  8. BinaryNode(AnyType theElement)
  9. {
  10. this(theElement, null, null);
  11. }
  12. BinaryNode(AnyType theElement, BinaryNode<AnyType> lt, BinaryNode<AnyType> rt)
  13. {
  14. element = theElement;
  15. left = lt;
  16. right = rt;
  17. }
  18. AnyType element;
  19. BinaryNode<AnyType> left;
  20. BinaryNode<AnyType> right;
  21. }
  22. private BinaryNode<AnyType> root;
  23. public void insert(AnyType x)
  24. {
  25. root = insert(x, root);
  26. }
  27. public boolean isEmpty()
  28. {
  29. return root == null;
  30. }
  31. private BinaryNode<AnyType> insert(AnyType x, BinaryNode<AnyType> t)
  32. {
  33. if(t == null)
  34. {
  35. return new BinaryNode<>(x, null, null);
  36. }
  37. int compareResult = x.compareTo(t.element);
  38. if(compareResult < 0)
  39. {
  40. t.left = insert(x, t.left);
  41. }
  42. else if(compareResult > 0)
  43. {
  44. t.right = insert(x, t.right);
  45. }
  46. else
  47. {
  48. ;
  49. }
  50. return t;
  51. }
  52. /**
  53. * 前序遍历
  54. * 递归
  55. */
  56. public void preOrder(BinaryNode<AnyType> Node)
  57. {
  58. if (Node != null)
  59. {
  60. System.out.print(Node.element + " ");
  61. preOrder(Node.left);
  62. preOrder(Node.right);
  63. }
  64. }
  65. /**
  66. * 中序遍历
  67. * 递归
  68. */
  69. public void midOrder(BinaryNode<AnyType> Node)
  70. {
  71. if (Node != null)
  72. {
  73. midOrder(Node.left);
  74. System.out.print(Node.element + " ");
  75. midOrder(Node.right);
  76. }
  77. }
  78. /**
  79. * 后序遍历
  80. * 递归
  81. */
  82. public void posOrder(BinaryNode<AnyType> Node)
  83. {
  84. if (Node != null)
  85. {
  86. posOrder(Node.left);
  87. posOrder(Node.right);
  88. System.out.print(Node.element + " ");
  89. }
  90. }
  91. /*
  92. * 层序遍历
  93. * 递归
  94. */
  95. public void levelOrder(BinaryNode<AnyType> Node) {
  96. if (Node == null) {
  97. return;
  98. }
  99. int depth = depth(Node);
  100. for (int i = 1; i <= depth; i++) {
  101. levelOrder(Node, i);
  102. }
  103. }
  104. private void levelOrder(BinaryNode<AnyType> Node, int level) {
  105. if (Node == null || level < 1) {
  106. return;
  107. }
  108. if (level == 1) {
  109. System.out.print(Node.element + " ");
  110. return;
  111. }
  112. // 左子树
  113. levelOrder(Node.left, level - 1);
  114. // 右子树
  115. levelOrder(Node.right, level - 1);
  116. }
  117. public int depth(BinaryNode<AnyType> Node) {
  118. if (Node == null) {
  119. return 0;
  120. }
  121. int l = depth(Node.left);
  122. int r = depth(Node.right);
  123. if (l > r) {
  124. return l + 1;
  125. } else {
  126. return r + 1;
  127. }
  128. }
  129. /**
  130. * 前序遍历
  131. * 非递归
  132. */
  133. public void preOrder1(BinaryNode<AnyType> Node)
  134. {
  135. Stack<BinaryNode> stack = new Stack<>();
  136. while(Node != null || !stack.empty())
  137. {
  138. while(Node != null)
  139. {
  140. System.out.print(Node.element + " ");
  141. stack.push(Node);
  142. Node = Node.left;
  143. }
  144. if(!stack.empty())
  145. {
  146. Node = stack.pop();
  147. Node = Node.right;
  148. }
  149. }
  150. }
  151. /**
  152. * 中序遍历
  153. * 非递归
  154. */
  155. public void midOrder1(BinaryNode<AnyType> Node)
  156. {
  157. Stack<BinaryNode> stack = new Stack<>();
  158. while(Node != null || !stack.empty())
  159. {
  160. while (Node != null)
  161. {
  162. stack.push(Node);
  163. Node = Node.left;
  164. }
  165. if(!stack.empty())
  166. {
  167. Node = stack.pop();
  168. System.out.print(Node.element + " ");
  169. Node = Node.right;
  170. }
  171. }
  172. }
  173. /**
  174. * 后序遍历
  175. * 非递归
  176. */
  177. public void posOrder1(BinaryNode<AnyType> Node)
  178. {
  179. Stack<BinaryNode> stack1 = new Stack<>();
  180. Stack<Integer> stack2 = new Stack<>();
  181. int i = 1;
  182. while(Node != null || !stack1.empty())
  183. {
  184. while (Node != null)
  185. {
  186. stack1.push(Node);
  187. stack2.push(0);
  188. Node = Node.left;
  189. }
  190. while(!stack1.empty() && stack2.peek() == i)
  191. {
  192. stack2.pop();
  193. System.out.print(stack1.pop().element + " ");
  194. }
  195. if(!stack1.empty())
  196. {
  197. stack2.pop();
  198. stack2.push(1);
  199. Node = stack1.peek();
  200. Node = Node.right;
  201. }
  202. }
  203. }
  204. /*
  205. * 层序遍历
  206. * 非递归
  207. */
  208. public void levelOrder1(BinaryNode<AnyType> Node) {
  209. if (Node == null) {
  210. return;
  211. }
  212. BinaryNode<AnyType> binaryNode;
  213. Queue<BinaryNode> queue = new LinkedList<>();
  214. queue.add(Node);
  215. while (queue.size() != 0) {
  216. binaryNode = queue.poll();
  217. System.out.print(binaryNode.element + " ");
  218. if (binaryNode.left != null) {
  219. queue.offer(binaryNode.left);
  220. }
  221. if (binaryNode.right != null) {
  222. queue.offer(binaryNode.right);
  223. }
  224. }
  225. }
  226. public static void main( String[] args )
  227. {
  228. int[] input = {4, 2, 6, 1, 3, 5, 7, 8, 10};
  229. Tree<Integer> tree = new Tree<>();
  230. for(int i = 0; i < input.length; i++)
  231. {
  232. tree.insert(input[i]);
  233. }
  234. System.out.print("递归前序遍历 :");
  235. tree.preOrder(tree.root);
  236. System.out.print("\n非递归前序遍历:");
  237. tree.preOrder1(tree.root);
  238. System.out.print("\n递归中序遍历 :");
  239. tree.midOrder(tree.root);
  240. System.out.print("\n非递归中序遍历 :");
  241. tree.midOrder1(tree.root);
  242. System.out.print("\n递归后序遍历 :");
  243. tree.posOrder(tree.root);
  244. System.out.print("\n非递归后序遍历 :");
  245. tree.posOrder1(tree.root);
  246. System.out.print("\n递归层序遍历:");
  247. tree.levelOrder(tree.root);
  248. System.out.print("\n非递归层序遍历 :");
  249. tree.levelOrder1(tree.root);
  250. }
  251. }

  在以上代码中,preOrder1、midOrder1、posOrder1、levelOrder1四个函数,分别代表了非递归实现的二叉树前序、中序、后序、层序遍历遍历。

Java实现二叉树的前序、中序、后序遍历(非递归方法)的更多相关文章

  1. Java 重建二叉树 根据前序中序重建二叉树

    题目:输入某二叉树的前序遍历和中序遍历的结果,请重建出该二叉树.假设输入的前序遍历和中序遍历的结果中都不含重复的数字.例如输入前序遍历序列{1,2,4,7,3,5,6,8}和中序遍历序列{4,7,2, ...

  2. 分别求二叉树前、中、后序的第k个节点

    一.求二叉树的前序遍历中的第k个节点 //求先序遍历中的第k个节点的值 ; elemType preNode(BTNode *root,int k){ if(root==NULL) return ' ...

  3. 【LeetCode】二叉搜索树的前序,中序,后续遍历非递归方法

    前序遍历 public List<Integer> preorderTraversal(TreeNode root) { ArrayList<Integer> list = n ...

  4. 算法进阶面试题03——构造数组的MaxTree、最大子矩阵的大小、2017京东环形烽火台问题、介绍Morris遍历并实现前序/中序/后序

    接着第二课的内容和带点第三课的内容. (回顾)准备一个栈,从大到小排列,具体参考上一课.... 构造数组的MaxTree [题目] 定义二叉树如下: public class Node{ public ...

  5. 二叉树 遍历 先序 中序 后序 深度 广度 MD

    Markdown版本笔记 我的GitHub首页 我的博客 我的微信 我的邮箱 MyAndroidBlogs baiqiantao baiqiantao bqt20094 baiqiantao@sina ...

  6. 前序+中序->后序 中序+后序->前序

    前序+中序->后序 #include <bits/stdc++.h> using namespace std; struct node { char elem; node* l; n ...

  7. SDUT OJ 数据结构实验之二叉树八:(中序后序)求二叉树的深度

    数据结构实验之二叉树八:(中序后序)求二叉树的深度 Time Limit: 1000 ms Memory Limit: 65536 KiB Submit Statistic Discuss Probl ...

  8. SDUT-2804_数据结构实验之二叉树八:(中序后序)求二叉树的深度

    数据结构实验之二叉树八:(中序后序)求二叉树的深度 Time Limit: 1000 ms Memory Limit: 65536 KiB Problem Description 已知一颗二叉树的中序 ...

  9. 给出 中序&后序 序列 建树;给出 先序&中序 序列 建树

    已知 中序&后序  建立二叉树: SDUT 1489 Description  已知一棵二叉树的中序遍历和后序遍历,求二叉树的先序遍历 Input  输入数据有多组,第一行是一个整数t (t& ...

  10. 【C&数据结构】---关于链表结构的前序插入和后序插入

    刷LeetCode题目,需要用到链表的知识,忽然发现自己对于链表的插入已经忘得差不多了,以前总觉得理解了记住了,但是发现真的好记性不如烂笔头,每一次得学习没有总结输出,基本等于没有学习.连复盘得机会都 ...

随机推荐

  1. PHP运行方式

    原文链接:http://www.cnblogs.com/xia520pi/p/3914964.html 1.运行模式 关于PHP目前比较常见的五大运行模式: 1)CGI(通用网关接口 / Common ...

  2. [Unity]Unity开发NGUI代码实现ScrollView(滚动视图)

    Unity开发NGUI代码实现ScrollView(滚动视图) 下载NGUI包 导入NGUI3.9.1版本package 链接: http://pan.baidu.com/s/1mgksPBU 密码: ...

  3. 有趣的keil MDK细节(转)

    源:有趣的keil MDK细节 1.MDK中的char类型的取值范围是? 在MDK中,默认情况下,char 类型的数据项是无符号的,所以它的取值范围是0-255.它们可以显式地声明为signed ch ...

  4. 在MAC上安装GitHub DeskTop

    下载Git工具:下载链接 https://git-scm.com/downloads/ 然后配置Git:配置教程链接  http://jingyan.baidu.com/article/ceb9fb1 ...

  5. LPC2478的SPI使用

    LPC2478的spi使用 LPC2748具有一个SPI控制器,可以当做SPI主机或者从机使用,有以下特性 其使用起来很方便,并且支持中断,使用的寄存器如下 基本上,使用起来就是设置控制为,CPOL ...

  6. 解决tomcat运行报错java.lang.UnsatisfiedLinkError: apache-tomcat-7.0.37\bin\tcnative-1.dll:Can load AMD 64

    http://www.apache.org/dist/tomcat/tomcat-connectors/native/ 到该地址下下载一个tomcat-native-1.2.2-win32-bin压缩 ...

  7. C#生成随机验证吗例子

    C#生成随机验证吗例子: public class ValidateCode : IHttpHandler, IRequiresSessionState { HttpContext context; ...

  8. 每个Javascript开发者都应当知道的那些事

    每个Javascript开发者都应当知道的那些事 2015-06-07 前端大全 (点击上方蓝字,可快速关注我们) Javascript是一种日益增长的语言,特别是现在ECMAScript规范按照每年 ...

  9. Unity中使用扩展方法解决foreach导致的GC

    对于List这种顺序表,我们解决的时候还是可以使用for代替foreach即可.但是对于非顺序表,比如Dictionary或者Set之类,我们可以扩展方法Foreach,ForeachKey和Fore ...

  10. linux mint运行docker

    1,sudo apt-get install docker.io 或者sudo apt-get install docker* 2,安装好之后 sudo docker -d 启动进程提示: yimiy ...