二叉树的三种非递归遍历和morris遍历

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
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值