面試題 32-II 從上到下打印二叉樹

題目描述

題目轉載自LeetCode

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

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

返回其層次遍歷結果:

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

提示:

節點總數 <= 1000

題目解析

轉載自LeetCode作者:Krahets

算法流程:

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

代碼實現

/**
 * 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) {
        //linkedlist增刪快
        Queue<TreeNode> queue = new LinkedList<>();
        //arraylist get和set操作快
        List<List<Integer>> res = new ArrayList<>();
        //把根節點加入隊列
        if(root!=null) queue.add(root);
        while(!queue.isEmpty()){
            //tmp用於存儲每一行的節點值
            List<Integer> tmp = new ArrayList<>();
            for(int i=queue.size();i>0;i--){
                TreeNode node = queue.poll();
                tmp.add(node.val);
                if(node.left!=null) queue.add(node.left);
                if(node.right!=null) queue.add(node.right);
            }
            res.add(tmp);
        }
        return res;
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章