파비의 매일매일 공부기록

2023.04.20 Today's Challenge 본문

Problem Solving/LeetCode

2023.04.20 Today's Challenge

fabichoi 2023. 4. 20. 23:45

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

 

Maximum Width of Binary Tree - LeetCode

Can you solve this real interview question? Maximum Width of Binary Tree - Given the root of a binary tree, return the maximum width of the given tree. The maximum width of a tree is the maximum width among all levels. The width of one level is defined as

leetcode.com

BFS로 푸는 문제!

class Solution:
    def widthOfBinaryTree(self, root: Optional[TreeNode]) -> int:
        q, width = deque([(root, 0)]), 0
        while q:
            width = max(width, q[-1][1] - q[0][1])
            for _ in range(len(q)):
                node, k = q.popleft()
                if node.left:
                    q.append((node.left, k * 2 - 1))
                if node.right:
                    q.append((node.right, k * 2))
        return width + 1
반응형

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

2023.04.22 Today's Challenge  (0) 2023.04.22
2023.04.21 Today's Challenge  (0) 2023.04.21
2023.04.19 Today's Challenge  (0) 2023.04.19
2023.04.18 Today's Challenge  (0) 2023.04.18
2023.04.17 Today's Challenge  (0) 2023.04.17
Comments