非递归进行前序,中序,后序遍历

对于二叉树的前序,中序,后序遍历,相信利用递归来做我们已经非常熟悉了,而如何非递归进行前序,中序,后序呢?

一、前序

递归实现:

 public void preOrder_recursive(TreeNode root){
        if(root==null){
            System.out.print("null ");
            return;
        }
        System.out.print(root.val+" ");
        preOrder_recursive(root.left);
        preOrder_recursive(root.right);
    }

非递归实现:

//非递归用栈
    public void preOrder(TreeNode root){
        Stack<TreeNode> s=new Stack<>();
        TreeNode cur=root;
        while(cur!=null||!s.empty()){
            while(cur!=null){
                s.push(cur);
                System.out.print(cur.val+" ");
                cur=cur.left;
            }
            TreeNode top=s.pop();
            cur=top.right;
        }
    }

二、中序

递归实现:

public void Inorder_recursive(TreeNode root){
        if(root==null){
            return ;
        }
        Inorder_recursive(root.left);
        System.out.print(root.val+" ");
        Inorder_recursive(root.right);
    }

非递归实现:

public void Inorder(TreeNode root){
        Stack<TreeNode> s=new Stack<>();
        TreeNode cur=root;
        while(cur!=null||!s.empty()){
            while(cur!=null){
                s.push(cur);
                cur=cur.left;
            }
            TreeNode top=s.pop();
            System.out.print(top.val+" ");
            cur=top.right;
        }
    }

三、后序

递归:

public void PostOrder_recursive(TreeNode root){
        if(root==null){
            return ;
        }
        PostOrder_recursive(root.left);
        PostOrder_recursive(root.right);
        System.out.print(root.val+" ");
    }

非递归:

 public void PostOrder(TreeNode root){
        Stack<TreeNode> s=new Stack<>();
        TreeNode cur=root;
        TreeNode pre=root;
        while(cur!=null||!s.empty()){
            //一直找,找到最左边
            while(cur!=null){
                s.push(cur);
                cur=cur.left;
            }
            TreeNode top=s.peek();
            cur=top.right;
            if(cur==null||cur==pre){
                System.out.print(top.val+" ");
                pre=s.pop();
                cur=null;
            }
        }
    }

  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值