[LeetCode](面試題32 - II)從上到下打印二叉樹 II

題目

從上到下按層打印二叉樹,同一層的節點按從左到右的順序打印,每一層打印到一行。

例如:
給定二叉樹: [3,9,20,null,null,15,7],

    3
   / \
  9  20
    /  \
   15   7

返回其層次遍歷結果:

[
  [3],
  [9,20],
  [15,7]
]

提示:

  1. 節點總數 <= 1000

解題思路

二叉樹的“從上至下”打印(即按層打印),又稱爲二叉樹的層次遍歷,可以通過 BFS 來實現,而 BFS 又通常藉助隊列來實現。

算法步驟:

  • 1)特例處理:當樹的根節點爲空,則直接返回空列表 [] ;
  • 2)初始化:結果列表 res = [] ,包含根節點的隊列 queue = [root] ;
  • 3)進入 BFS 循環:當隊列 queue 不爲空時進入循環:
    • 3.1)新建一個臨時列表 tmp ,用於存儲當前層打印結果;
    • 3.2)打印當前層節點,循環次數爲當前層節點數(即隊列 queue 長度):
      • 3.2.1)隊首元素出隊,記爲 cur;
      • 3.2.2)打印:將 cur.val 添加至列表 tmp 尾部;
      • 3.2.3)添加子節點:若 cur 的左(右)子節點不爲空,則將左(右)子節點分別加入隊列 queue ;
    • 3.3)將當前層結果 tmp 添加入 res 。
  • 4)返回值:返回結果列表 res 即可。

複雜度分析:
時間複雜度:O(N):N 爲二叉樹的節點數量,即 BFS 需循環 N 次。
空間複雜度:O(N):最差情況下,即當樹爲平衡二叉樹時,最多有 N/2 個樹節點同時在 queue 中,需要 O(N) 大小的額外空間。

代碼

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    public List<List<Integer>> levelOrder(TreeNode root) {
        List<List<Integer>> res = new ArrayList<>();
        Deque<TreeNode> queue = new LinkedList<>();
        if(root == null){
            return res;
        }
        queue.offer(root);
        while(!queue.isEmpty()){
            // 本層節點數
            int n = queue.size();
            List<Integer> tmp = new ArrayList<>();
            for(int i=0; i<n; i++){
                TreeNode cur = queue.poll();
                tmp.add(cur.val);
                if(cur.left != null){
                    queue.offer(cur.left);
                }
                if(cur.right != null){
                    queue.offer(cur.right);
                }
            }
            res.add(tmp);
        }
        return res;
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章