[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;
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章