二叉树的四种遍历方式

二叉树是一种很常见的数据结构,其结构如下图:
这里写图片描述

下面接受他的四种遍历方式:

  • 先序(先根)遍历:即先访问根节点,再访问左孩子和右孩子
  • 中序遍历:
  • 后序遍历:
  • 层次遍历:按照所在层数,从下往上遍历

前提:这里先给出测试中的二叉树结构,如下图所示
这里写图片描述
该二叉树对应的几种遍历方式的结果顺序:
先序遍历:10->6->4->8->14->12->16
中序遍历:4->6->8->10->12->14->16
后序遍历:4->8->6->12->16->14->10
层次遍历:10->6->14->4->8->12->16

接下来是相应的代码实现:

public class Main {

    public static void main(String[] args) {

        TreeNode root = initTreeNode();

        levelIterator(root);
//      PreNode(root);
//      InNode(root);
//      ProNode(root);
    }

    /**
     * 层次遍历
     * @param root 根结点
     */
    public static void levelIterator(TreeNode root) {

        if (root == null) {
            return;
        }
        LinkedList<TreeNode> queue = new LinkedList<>();
        TreeNode current = null;
        queue.offer(root);//进队
        while (!queue.isEmpty()) {
            current = queue.poll();//出队
            System.out.print(current.val + "->");
            if (current.left != null) {
                queue.offer(current.left);
            }
            if (current.right != null) {
                queue.offer(current.right);
            }
        }

    }

    /**
     * 先序遍历
     * @param root 根结点
     */
    public static void PreNode(TreeNode root) {

        if (root != null) {
            System.out.print(root.val + "->");
            PreNode(root.left);
            PreNode(root.right);
        }

    }

    /**
     * 中序遍历
     * @param root 根结点
     */
    public static void InNode(TreeNode root) {
        if (root != null) {
            InNode(root.left);
            System.out.print(root.val + "->");
            InNode(root.right);
        }
    }

    /**
     * 后序遍历
     * @param root
     */
    public static void ProNode(TreeNode root) {
        if (root != null) {
            ProNode(root.left);
            ProNode(root.right);
            System.out.print(root.val + "->");
        }
    }

    /**
     * 初始化二叉树
     * @return 二叉树的根结点
     */
    public static TreeNode initTreeNode() {

        TreeNode root = new TreeNode(10);
        root.left = new TreeNode(6);
        root.right = new TreeNode(14);
        root.left.left = new TreeNode(4);
        root.left.right = new TreeNode(8);
        root.right.left = new TreeNode(12);
        root.right.right = new TreeNode(16);
        return root;
    }

    /**
     * 二叉树的数据结构
     */
    public static class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;

        TreeNode(int x) {
            val = x;
        }
    }

}

对于前、中、后序遍历,使用的是递归的思想,按照其先后顺序输出即可实现。
层次遍历则是使用到了队列,具体过程用一张图表示。
这里写图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值