All Articles

BFSμ—μ„œ 깊이 λ³„λ‘œ μž‘μ—…ν•˜κΈ°

Binary Tree Level Order Traversal

Q102 Q637

BFS λŠ” BFS 인데 깊이 λ³„λ‘œ 무언가 ν•˜λŠ” λ¬Έμ œκ°€ μžˆμ—ˆμŒκ·Έλ•ŒλŠ” 깊이 λ³„λ‘œ μž‘μ—…μ„ μ‹œμž‘ν•˜κΈ° μ „, 끝에 처리λ₯Ό ν•΄μ£Όλ©΄ 됨

기둝해두고 싢은건 queue λͺ¨λ“ˆμ„ μ“°κΈ° 싫을 λ•ŒλŠ” κ·Έλƒ₯ λ¦¬μŠ€νŠΈμ—λ‹€ append ν•˜κ³  ν•œ 번 reverse ν•΄μ„œ 계속 pop ν•˜λ©΄ λ‚˜λ¦„ FIFO λŠλ‚Œ λ‚˜κ²Œ μ“Έ 수 μžˆλ‹€λŠ”κ±°.

import queue

class Solution:
    def levelOrder(self, root):
        """
        :type root: TreeNode
        :rtype: List[List[int]]
        """
        res = []
        if not root:
            return res
        q = [root]
        while q:
            level_roots = []
            childs = []
            q.reverse()
            while q:
                node = q.pop()
                level_roots.append(node.val)
                if node.left:
                    childs.append(node.left)
                if node.right:
                    childs.append(node.right)
            res.append(level_roots)
            q = childs
        return res

Published Apr 14, 2018

If I keep marking the dots, someday they will πŸ”—πŸ”—