Tensorum
YouTubeಕಲಿಯಲು ಪ್ರಾರಂಭಿಸಿ
LeetCode 662 · BFS / Level Order

Maximum Width of Binary Tree

LeetCode 662 · ಮಧ್ಯಮ · ಪರಿಹಾರ, intuition ಮತ್ತು ಹಂತ ಹಂತದ ವಾಕ್‌ಥ್ರೂ

Heap indices per level, normalised by the level's first index.

ಮಧ್ಯಮTreeDepth-First SearchBreadth-First SearchBinary Tree
LeetCode ನಲ್ಲಿ ತೆರೆಯಿರಿ ↗

ನಾನು Maximum Width of Binary Tree (LeetCode 662) ಅನ್ನು ಹೀಗೆ ಪರಿಹರಿಸಿದೆ — BFS / Level Order ಪ್ಯಾಟರ್ನ್‌ನ ಒಂದು ಮಧ್ಯಮ ಪ್ರಾಬ್ಲಮ್. ಕೆಳಗೆ: intuition, ಹಂತ ಹಂತದ approach, ನನ್ನ accepted Python ಕೋಡ್, animated test cases ಮತ್ತು line-by-line debugger.

ಕೆಳಗಿನ ವಿವರಣೆ ಇಂಗ್ಲಿಷ್‌ನಲ್ಲಿದೆ.

Intuition

Number nodes like a heap: children of index i are 2i+1 and 2i+2. A level's width is last index − first index + 1. To stop the numbers from exploding on deep trees, subtract the level's minimum index before computing children.

Approach

  1. 1

    BFS with (node, index) pairs.

  2. 2

    For each level, note the first and last indices.

  3. 3

    Push children with 2·index+1 / +2 minus the level's minimum.

  4. 4

    Track last − first + 1.

ನಾನು ಹೇಗೆ ಪರಿಹರಿಸಿದೆ

BFS with heap indicesPythonO(n) time
class Solution:
    def widthOfBinaryTree(self, root):
        mx = float("-inf")
        queue = [[root, 0]]
        fast = 0
        last = 0
        while queue:
            size = len(queue)
            minIndex = queue[0][1]
            mx = max(size, mx)
            for i in range(size):
                node, index = queue.pop(0)
                if i == 0:
                    fast = index
                if i == size - 1:
                    last = index
                if node.left:
                    queue.append([node.left, (2 * index + 1) - minIndex])
                if node.right:
                    queue.append([node.right, (2 * index + 2) - minIndex])
            mx = max(mx, last - fast + 1)
        return mx
ಸ್ಟೆಪ್-ಥ್ರೂ ಲೋಡ್ ಆಗುತ್ತಿದೆ…

Maximum Width of Binary Tree — ಪದೇ ಪದೇ ಕೇಳುವ ಪ್ರಶ್ನೆಗಳು

Maximum Width of Binary Tree ಹಿಂದಿನ intuition ಏನು?

Number nodes like a heap: children of index i are 2i+1 and 2i+2. A level's width is last index − first index + 1. To stop the numbers from exploding on deep trees, subtract the level's minimum index before computing children.

Maximum Width of Binary Tree (LeetCode 662) ಅನ್ನು ಹೇಗೆ ಪರಿಹರಿಸುವುದು?

1. BFS with (node, index) pairs. 2. For each level, note the first and last indices. 3. Push children with 2·index+1 / +2 minus the level's minimum. 4. Track last − first + 1.

Maximum Width of Binary Tree ನ time ಮತ್ತು space complexity ಎಷ್ಟು?

Time: O(n). Space: O(n). (Accepted approach: BFS with heap indices.)

Maximum Width of Binary Tree ನಲ್ಲಿ ಸಾಮಾನ್ಯ ತಪ್ಪುಗಳು ಯಾವುವು?

Without normalising, indices overflow in languages with fixed-width ints.