二叉樹之深度優先遍歷與廣度優先遍歷

  • 通過二叉樹的前序和中序遍歷確定二叉樹:就是找到中序遍歷中二叉樹的根結點的下標,然後根據左右兩子樹進行遞歸
  • 二叉樹的深度優先遍歷和廣度優先遍歷:就是利用棧和隊列進行存取元素
/*
 * @Author:Beer
 * @Date:2019-10-06
 * @Description:
 * 通過二叉樹的前序和中序遍歷確定二叉樹:就是找到中序遍歷中二叉樹的根結點的下標,然後根據左右兩子樹進行遞歸
 * 二叉樹的深度優先遍歷和廣度優先遍歷:就是利用棧和隊列進行存取元素
 */

import java.util.*;

class TreeNode {
    TreeNode left;
    TreeNode right;
    int val;

    public TreeNode(int val) {
        this.val = val;
    }
}

public class TestLeverTree {
    public static void main(String[] args) {
        int[] pre = {1, 2, 4, 7, 3, 5, 6, 8};
        int[] ino = {4, 7, 2, 1, 5, 3, 8, 6};
        //構造二叉樹
        TreeNode root = buildTree(pre, 0, pre.length - 1, ino, 0, ino.length - 1);
        //進行二叉樹的層次遍歷
        levelTree(root);
        System.out.println();
        //非遞歸版本的深度優先遍歷
        depthThree(root);
    }

    /**
     * 通過二叉樹的前序、中序構造二叉樹
     *
     * @param pre
     * @param ps
     * @param pe
     * @param ino
     * @param is
     * @param ie
     */
    public static TreeNode buildTree(int[] pre, int ps, int pe, int[] ino, int is, int ie) {
        if (ps > pe) {
            return null;
        }
        int val = pre[ps];
        int index = is;
        while (is < ie && ino[index] != val) {
            index++;
        }
        if (index > ie) {
            throw new RuntimeException("Illegal input");
        }
        TreeNode node = new TreeNode(val);
        // 遞歸構建當前根結點的左子樹,左子樹的元素個數:index-is+1個
        // 左子樹對應的前序遍歷的位置在[ps+1, ps+index-is]
        // 左子樹對應的中序遍歷的位置在[is, index-1]
        node.left = buildTree(pre, ps + 1, ps + index - is, ino, is, index - 1);
        // 遞歸構建當前根結點的右子樹,右子樹的元素個數:ie-index個
        // 右子樹對應的前序遍歷的位置在[ps+index-is+1, pe]
        // 右子樹對應的中序遍歷的位置在[index+1, ie]
        node.right = buildTree(pre, ps + index - is + 1, pe, ino, index + 1, ie);
        return node;
    }

    /**
     * 二叉樹的層次遍歷
     *
     * @param root
     */
    public static void levelTree(TreeNode root) {
        Queue<TreeNode> queue = new LinkedList<>();
        queue.add(root);
        while (!queue.isEmpty()) {
            TreeNode node = queue.poll();
            System.out.print(node.val);
            if (node.left != null) {
                queue.add(node.left);
            }
            if (node.right != null) {
                queue.add(node.right);
            }

        }
    }

    /**
     * 二叉樹的深度優先遍歷
     * @param root
     */
    public static void depthThree(TreeNode root) {
        Stack<TreeNode> stack = new Stack<>();
        stack.add(root);
        while (!stack.isEmpty()) {
            TreeNode node = stack.pop();
            System.out.print(node.val);
            if (node.right != null) {
                stack.add(node.right);
            }
            if (node.left != null) {
                stack.add(node.left);
            }
        }
    }
}

結果:
12345678
12473568

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章