Vertical Order Traversal of a Binary Tree
LeetCode 987 · கடினம் · தீர்வு, intuition & படிப்படியான வாக்த்ரூ
Map column → row → sorted values.
நான் Vertical Order Traversal of a Binary Tree (LeetCode 987) ஐ இப்படித் தீர்த்தேன் — BFS / Level Order பேட்டர்னின் ஒரு கடினம் பிராப்ளம். கீழே: intuition, படிப்படியான approach, என் accepted Python கோட், animated test cases மற்றும் line-by-line debugger.
கீழேயுள்ள விளக்கம் ஆங்கிலத்தில் உள்ளது.
Intuition
Give every node a column (left −1, right +1) and a row (depth). Group values by column, then by row, sorting values that share the same row and column. Output columns from left to right.
Approach
- 1
BFS carrying (node, column, row).
- 2
Insert node.val into map[column][row] and keep that list sorted.
- 3
Sort columns; within a column rows are already in BFS order.
- 4
Concatenate each column's lists.
நான் எப்படித் தீர்த்தேன்
BFS + nested mapsPythonO(n log n) time
class Solution:
def verticalTraversal(self, root):
queue = [[root, 0, 0]]
lineMap = {}
res = []
while queue:
node, line, level = queue.pop(0)
lineMap.setdefault(line, {})
lineMap[line].setdefault(level, [])
lineMap[line][level].append(node.val)
lineMap[line][level].sort()
if node.left:
queue.append([node.left, line - 1, level + 1])
if node.right:
queue.append([node.right, line + 1, level + 1])
for line in sorted(lineMap):
res.append([])
for level, values in lineMap[line].items():
res[-1].extend(values)
return resVertical Order Traversal of a Binary Tree — அடிக்கடி கேட்கப்படும் கேள்விகள்
Vertical Order Traversal of a Binary Tree பின்னாலுள்ள intuition என்ன?
Give every node a column (left −1, right +1) and a row (depth). Group values by column, then by row, sorting values that share the same row and column. Output columns from left to right.
Vertical Order Traversal of a Binary Tree (LeetCode 987) ஐ எப்படித் தீர்ப்பது?
1. BFS carrying (node, column, row). 2. Insert node.val into map[column][row] and keep that list sorted. 3. Sort columns; within a column rows are already in BFS order. 4. Concatenate each column's lists.
Vertical Order Traversal of a Binary Tree இன் time மற்றும் space complexity என்ன?
Time: O(n log n). Space: O(n). (Accepted approach: BFS + nested maps.)
Vertical Order Traversal of a Binary Tree இல் பொதுவான தவறுகள் என்ன?
Ties at the same row and column are broken by value, not left/right.