二叉樹的層次遍歷(BFS)


今日在LeetCode平台上刷到一道Medium難度的題,要求是二叉樹的層次遍歷。個人認為難度並不應該定在Medium, 應該是Easy比較合適,因為並沒有復雜的算法邏輯,也沒有corner cases

 

 

 

class Solution {
    public List<List<Integer>> levelOrder(TreeNode root) {
        //using queue
        List<List<Integer>> res= new ArrayList<>();
        if(root == null) return res;
        Queue<TreeNode> q = new LinkedList<>();
        q.offer(root);
        while(!q.isEmpty()){
            int len = q.size();
            List<Integer> tmp = new ArrayList<>();
            while(len-->0){
                TreeNode t = q.poll();
                tmp.add(t.val);
                if(t.left!=null) q.offer(t.left);
                if(t.right!=null) q.offer(t.right);
            }
            res.add(tmp);
        }
        return res;
    }
}


免責聲明!

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



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