소프트웨어에 대한 모든 것

LeetCode 풀기 - 662. Maximum Width of Binary Tree 본문

알고리즘/LeetCode

LeetCode 풀기 - 662. Maximum Width of Binary Tree

앤테바 2022. 2. 27. 11:56
반응형

662. Maximum Width of Binary Tree

https://leetcode.com/problems/maximum-width-of-binary-tree/

 

Maximum Width of Binary Tree - 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

문제)

솔루션1) 재귀

문제에 대한 이해를 확실히 하지 못해서 많이 헤맸습니다.

문제가 원하는 바를 다시 정리하자면,

 

"바이너리 트리에서 모든 레벨에서의 최대 폭을 리턴하는 것'입니다.

 

depth 2에서 최대 폭 4가 가장 큼

문제를 해결하기 위해서는,

1) 각 레벨에서의 폭을 계산한다.

2) 모든 레벨을 순회하면서 최대 폭을 찾는다.

 

 

바이너리 트리의 depth별 폭을 dict 형태로 계산해서 최대 폭을 계산하는 방법을 취합니다.

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
    def widthOfBinaryTree(self, root: Optional[TreeNode]) -> int:
        # key = depth, value=[column numbers]
        d = defaultdict(list)
        
        def recur(node, depth, column):
            if node is None: return            
            d[depth].append(column)            
            recur(node.left, depth+1, column*2)
            recur(node.right, depth+1, column*2+1)
            
        recur(root, depth=0, column=0)
        return max([(max(d[depth]) - min(d[depth]) + 1) for depth in d])

 

함께 보면 좋은 글:

https://leetcode.com/problems/maximum-width-of-binary-tree/discuss/750068/Simple-DFS-python-with-drawing-explanation

반응형
Comments