Maximum Width of Binary Tree
LeetCode 662 · நடுத்தரம் · தீர்வு, intuition & படிப்படியான வாக்த்ரூ
Heap indices per level, normalised by the level's first index.
நான் 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
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.
நான் எப்படித் தீர்த்தேன்
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 mxMaximum 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.