二叉树的三种非递归遍历和morris遍历
来源:互联网 发布:淘宝宝贝描述图片宽度 编辑:程序博客网 时间:2024/05/22 07:31
1、先序遍历
public static void printPreOrder(TreeNode node) { Queue<TreeNode> queue = new LinkedList<TreeNode>(); if (node == null) return; queue.offer(node); while (!queue.isEmpty()) { TreeNode temp = queue.poll(); System.out.println(temp.val); if (temp.left != null) queue.offer(temp.left); if (temp.right != null) queue.offer(temp.right); } }
2、中序遍历
public static void printInOrder(TreeNode node) { Stack<TreeNode> stack = new Stack<TreeNode>(); if (node == null) return; TreeNode temp = node; while (temp != null || !stack.isEmpty()) { while (temp != null) { stack.add(temp); temp = temp.left; } temp = stack.pop(); System.out.println(temp.val); temp = temp.right; } }
3、后序遍历
public static void printPostOrder(TreeNode node) { Stack<TreeNode> stack = new Stack<TreeNode>(); if (node == null)return; TreeNode temp = node; TreeNode pre = null; while (temp != null || !stack.isEmpty()) { while (temp != null) { stack.add(temp); temp = temp.left; } temp = stack.pop(); while (temp!=null&&(temp.right == null || pre == temp.right)) { pre = temp; System.out.println(temp.val); if(stack.isEmpty())return; temp=stack.pop(); } stack.add(temp); temp = temp.right; } }
4、morris遍历是一种很神奇的遍历,上述的三种方法和递归遍历方法都需要O(n)的时间,O(n)的空间,而morris遍历则只需要O(n)的时间,O(1)的空间。下面以morris中序遍历来说明。
算法伪代码如下:
MorrisInOrder():
while 没有结束
如果当前节点没有左孩子
访问该节点
转向该节点的右孩子
否则
找到左孩子的最右节点。
如果最右节点的右孩子不为空则说明最右节点已和当前节点连接,访问当前节点,并把最右节点的只有孩子置为空,转向当前节点的右孩子。
如果最右节点的右孩子为空,则使最右节点的右孩子指向当前节点,转向当前节点的左孩子。
public static void morrisInOrder(TreeNode root){ TreeNode cur=root; while(cur!=null){ if(cur.left==null){ System.out.println(cur.val); cur=cur.right; }else{ TreeNode temp=cur.left; while(temp.right!=null&&temp.right!=cur){ temp=temp.right; } if(temp.right==cur){ System.out.println(cur.val); temp.right=null; cur=cur.right; }else{ temp.right=cur; cur=cur.left; } } } }
0 0
- 二叉树的三种非递归遍历和morris遍历
- 二叉树的三种遍历方式(递归、非递归和Morris遍历)
- Morris Traversal - 不需递归和栈中序遍历二叉树
- 【树】二叉树的非递归遍历(栈&Morris)
- 二叉树的非递归遍历(Morris Traversal)
- 二叉树的inorder实现:递归、栈、Morris遍历
- 二叉树遍历(递归、非递归、Morris遍历)
- 二叉树遍历(递归、非递归、Morris遍历)
- Morris遍历二叉树
- Morris 二叉树遍历
- Morris遍历二叉树
- morris 遍历二叉树
- 二叉树的几种遍历方式浅析:递归遍历/堆栈遍历/层序遍历/Morris遍历
- 二叉树的几种遍历方式浅析:递归遍历/堆栈遍历/层序遍历/Morris遍历
- leetcode 99. Recover Binary Search Tree 二叉树非递归遍历,利用stack和morris遍历
- 二叉树问题---二叉树的前中后序的递归,非递归及Morris遍历
- 精妙的Morris二叉树遍历算法
- 精妙的Morris二叉树遍历算法
- 用C/C++扩展你的PHP 为你的php增加功能
- springmvc(基础一) @RequestMapping 用法详解之地址映射
- Phabricator命令行工具Arcanist的基本用法
- iptables命令详解(1)
- 在Linux下用C扩展PHP(打包成so)的方法
- 二叉树的三种非递归遍历和morris遍历
- 改造间隙扯淡1:机器人产品
- ViewPager的动画效果
- 阅读一百本计算机著作吧,少年
- Android性能调优利器StrictMode
- netmap分析(1)
- 屏蔽HTTPS证书验证下载apk安装包
- PHP ORM框架与简单代码实现—让OOP与关系数据库更融洽
- 设计模式--桥接模式