파비의 매일매일 공부기록

Today's Challenge 본문

Problem Solving/LeetCode

Today's Challenge

fabichoi 2022. 7. 13. 23:45

https://leetcode.com/problems/binary-tree-level-order-traversal/

 

Binary Tree Level Order Traversal - LeetCode

Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.

leetcode.com

이것도 며칠 전에 푼 전위 순회를 활용한 문제.
머릿속에서는 그래도 어떻게 풀면 되겠지 했는데.. 손이 안 가서 솔루션 참고 ㅠㅠ

class Solution:
    def levelOrder(self, root: Optional[TreeNode]) -> List[List[int]]: 
        
        def trans(k):
            if len(k) == 0:
                return            
            ans, nk = [], []
            for node in k:
                ans.append(node.val)
                
                if node.left:
                    nk.append(node.left)
                if node.right:
                    nk.append(node.right)            
            res.append(ans)
            trans(nk)
            
        res = []
        if root:
            trans([root])
        return res
반응형

'Problem Solving > LeetCode' 카테고리의 다른 글

Today's Challenge  (0) 2022.07.15
Today's Challenge  (0) 2022.07.14
Today's Challenge  (0) 2022.07.12
Today's Challenge  (0) 2022.07.11
Today's Challenge  (0) 2022.07.10
Comments