二叉樹的四種遍歷方式

二叉樹是一種很常見的數據結構,其結構如下圖:
這裏寫圖片描述

下面接受他的四種遍歷方式:

  • 先序(先根)遍歷:即先訪問根節點,再訪問左孩子和右孩子
  • 中序遍歷:
  • 後序遍歷:
  • 層次遍歷:按照所在層數,從下往上遍歷

前提:這裏先給出測試中的二叉樹結構,如下圖所示
這裏寫圖片描述
該二叉樹對應的幾種遍歷方式的結果順序:
先序遍歷: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;
        }
    }

}

對於前、中、後序遍歷,使用的是遞歸的思想,按照其先後順序輸出即可實現。
層次遍歷則是使用到了隊列,具體過程用一張圖表示。
這裏寫圖片描述

發佈了150 篇原創文章 · 獲贊 138 · 訪問量 26萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章