当前位置:   article > 正文

【Java数据结构】非递归遍历二叉树_二叉树非递归遍历算法 java

二叉树非递归遍历算法 java

目录

1. 定义二叉树结点类TreeNode

2. 前序遍历(非递归)

3. 中序遍历(非递归)

4. 后序遍历(非递归)


1. 定义二叉树结点类TreeNode

  1. public class TreeNode {
  2. char val;
  3. TreeNode left;
  4. TreeNode right;
  5. public TreeNode(char val) {
  6. this.val = val;
  7. }
  8. }

2. 前序遍历(非递归)

  1. public class TestBinaryTree {
  2. //前序遍历-非递归
  3. public preOrderTraversalNor (TreeNode root) {
  4. if (root == null) return;
  5. Stack<TreeNode> stack = new Stack<>();
  6. TreeNode cur = root;
  7. while (cur != null || !stack.empty()) {
  8. while (cur != null) {
  9. stack.push(cur);
  10. System.out.println(cur.val + " ");
  11. cur = cur.left;
  12. }
  13. //当cur.left为空时,弹栈
  14. TreeNode top = stack.pop();
  15. cur = top.right; //1.null 2.不是null的情况
  16. }
  17. }
  18. }

3. 中序遍历(非递归)

  1. void inOrderTraversalNor (TreeNode root) {
  2. if (root == null) return;
  3. Stack<TreeNode> stack = new Stack<>();
  4. TreeNode cur = root;
  5. while (cur != null || !stack.empty()) {
  6. while (cur != null) {
  7. stack.push(cur);
  8. cur = cur.left;
  9. }
  10. //当cur==null,说明走到了二叉树的最左侧,开始弹栈并打印
  11. TreeNode top = stack.pop();
  12. System.out.print(top.val+" ");
  13. cur = top.right;
  14. }
  15. System.out.println();
  16. }

4. 后序遍历(非递归

主要注意解决cur当前结点被打印 和 cur的右侧结点已被打印的问题

  1. void postOrderTraversalNor(TreeNode root) {
  2. if (root == null) return;
  3. Stack<TreeNode> stack = new Stack<>();
  4. TreeNode prev = null;
  5. TreeNode cur = root;
  6. while ( cur != null || !stack.empty()) {
  7. while ( cur != null) {
  8. stack.push(cur);
  9. cur = cur.left;
  10. }
  11. //走到最左边了
  12. cur = stack.peek();
  13. if (cur.right == null || cur.right == prev) { //cur.right == prev表明右结点被打印过了
  14. stack.pop();
  15. System.out.print(cur.val+" ");
  16. //记录被打印过的结点
  17. prev = cur;
  18. cur = null; //打印完一定要置空
  19. } else {
  20. cur = cur.right;
  21. }
  22. }
  23. }

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/从前慢现在也慢/article/detail/600907
推荐阅读
相关标签
  

闽ICP备14008679号