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

題目

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

例如:
給定二叉樹: [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)隊首元素出隊,記爲 cur;
    • 3.2)打印:將 cur.val 添加至列表 res 尾部;
    • 3.3)添加子節點:若 cur 的左(右)子節點不爲空,則將左(右)子節點分別加入隊列 queue ;
  • 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 int[] levelOrder(TreeNode root) {
        if(root == null){
            return new int[0];
        }
        ArrayList<Integer> list = new ArrayList<>();
        Deque<TreeNode> queue = new LinkedList<>();
        queue.offer(root);
        while(!queue.isEmpty()){
            TreeNode cur = queue.poll();
            list.add(cur.val);
            if(cur.left != null){
                queue.offer(cur.left);
            }
            if(cur.right != null){
                queue.offer(cur.right);
            }
        }
        int[] res = new int[list.size()];
        for(int i=0; i<list.size(); i++){
            res[i] = list.get(i);
        }
        return res;
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章