數據結構——二叉樹遍歷之“層遍歷”


系列文章:數據結構與算法系列——從菜鳥到入門

層次遍歷

二叉樹的層次遍歷是指,從二叉樹的第一層(根結點)開始,從上至下逐層遍歷,在同一層中從左至右依次遍歷。

  1. 設置一個隊列,將二叉樹的根結點放入隊列中。
  2. 將隊列中的頭結點出隊,賦值給臨時變量 temp,同時輸出打印 temp.val。
  3. 判斷 temp 是否有左結點和右結點,若有,分別將左、右結點放入隊列中。
  4. 重復步驟 2~3,直至隊列為空,表示二叉樹的層次遍歷結束。
private static void cengci(TreeNode root) {
    Queue<TreeNode> queue = new LinkedList<TreeNode>();
    queue.add(root);
    while (!queue.isEmpty()) {
        root = queue.poll();
        System.out.print(root.val+"-");
        if (root.left != null) {
            queue.add(root.left);
        }
        if (root.right != null) {
            queue.add(root.right);
        }
    }
}

按層打印

按層打印要求,在不同的層打印后加上換行。問題的關鍵就是如何知道該換行了。只需要兩個 node 類型的變量 last 和 nlast 就可以解決。同樣進行從左到右的寬度優先遍歷,如果發現遍歷到的結點等於 last,就該換行了。換行后將 last=nlast,繼續下一行的打印,重復過程,直到遍歷結束。

  1. 記二叉樹的根節點為 root,設置臨時變量 last 和 nlast。使 last=root、nlast=null。
  2. 申請一個空隊列 queue,將二叉樹的根結點放入隊列中。
  3. 從隊列中出隊頭結點 temp,判斷其是否有左孩子,若有,放入隊列中,將 nlast=temp.left。若有右孩子,也放入隊列中,將 nlast=temp.right。
  4. 若 last==root,那么打印換行,並將 last=nlast。
  5. 重復步驟 3~4,直至隊列為空,表示二叉樹的按層打印結束。
private static int[][] ceng(TreeNode root) {
    List<ArrayList<Integer>> resultMap = new ArrayList<ArrayList<Integer>>();
    ArrayList<Integer> ceng = new ArrayList<Integer>();
    Queue<TreeNode> queue = new LinkedList<TreeNode>();
    TreeNode last = root;
    TreeNode nlast = null;
    queue.offer(root);
    while (!queue.isEmpty()) {
        root = queue.poll();
        ceng.add(root.val);
        if (root.left != null) {
            queue.offer(root.left);
            nlast = root.left;
        }
        if (root.right != null) {
            queue.offer(root.right);
            nlast = root.right;
        }
        if (last==root) {
            last = nlast;
            resultMap.add(ceng);
            ceng = new ArrayList<Integer>();
        }
    }
    // 轉數組
    int[][] result = new int[resultMap.size()][];
    int i = 0;
    for (List<Integer> list : resultMap) {
        int[] temp = new int[list.size()];
        int j = 0;
        for (Integer integer : list) {
            temp[j++] = integer;
        }
        result[i++] = temp;
    }
    return result;
}

方法返回的是二維數組,一維代表二叉樹的層,二維代表每一層所有的結點。

參考資料

[1] 數據結構與算法分析——Java語言描述, 5.5.4 - 二叉樹的層次遍歷

[2] 程序員面試代碼指南, 第3章 - 二叉樹的按層打印


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM