二叉树的三种遍历方式(递归和非递归)

二叉树有三种遍历方式:前序、中序和后序。

递归遍历

1.前序遍历
    public static void preTraversal(Node root)
    {
        if(root==null)
            return ;

        System.out.println(root.value);
        preTraversal(root.left);
        preTraversal(root.right);
    }
2.中序遍历
    public static void midTraversal(Node root)
    {
        if(root == null)
            return ;
        midTraversal(root.left);
        System.out.println(root.value);
        midTraversal(root.right);
    }
3.后序遍历
    public static void neTraversal(Node root)
    {
        if(root==null)
            return;
        neTraversal(root.left);
        neTraversal(root.right);
        System.out.println(root.value);
    }

非递归方式实现

由于栈这种数据结构有“时光机”的性能,因此,利用栈进行非递归方式的遍历

1.前序遍历
    public static void preOrder(Node root)
    {
        if(root==null)
            return;

        Stack<Node> stack = new Stack<Node>();
        Node node = root;
        stack.push(node);
        while(!stack.isEmpty())
        {
            node = stack.pop();
            System.out.println(node.value);//遍历根节点

            if(node.right!=null)//如果左节点非空
                stack.push(node.right);
            if(node.left!=null)//右节点非空
                stack.push(node.left);
        }

    }
2.中序遍历
    public static void InO(Node root)
    {
        if (root == null)
            return;

        Stack<Node> stack = new Stack<>();
        Node node = root;
        while (node != null || !stack.isEmpty())
        {
            if (node != null)
            {
                stack.push(node);
                node = node.left;
            } else
            {
                node = stack.pop();
                System.out.println(node.value);
                node = node.right;
            }
        }
    }
3.后序遍历
    public static void houxubianli(Node root)
    {
        if (root == null)
            return;
        Stack<Node> s1 = new Stack<>();
        Stack<Node> s2 = new Stack<>();
        Node node = root;
        s1.push(node);
        while (!s1.isEmpty())
        {
            node = s1.pop();
            s2.push(node);
            if (node.right != null)
            {
                s1.push(node.right);
            }
            if (node.left != null)
            {
                s1.push(node.left);
            }
        }
        while(!s2.isEmpty())
        {
            System.out.println(s2.pop());
        }
    }

栈s1用于储存子节点,s2储存根节点

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值