HTMLify
30.py
Views: 7 | Author: prakhardoneria
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 | from collections import deque, defaultdict class Solution: def verticalOrder(self, root): if not root: return [] hd_map = defaultdict(list) queue = deque([(root, 0)]) min_hd, max_hd = 0, 0 while queue: node, hd = queue.popleft() hd_map[hd].append(node.data) min_hd = min(min_hd, hd) max_hd = max(max_hd, hd) if node.left: queue.append((node.left, hd - 1)) if node.right: queue.append((node.right, hd + 1)) result = [] for i in range(min_hd, max_hd + 1): if i in hd_map: result.append(hd_map[i]) return result |