987. Vertical Order Traversal of a Binary Tree Solution 1 (O(n*log(n))) # BFS # Definition for a binary tree node. # class TreeNode(object): # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution(object): def verticalTraversal(self, root): """ :type root: TreeNode :rtype: List[List[int]] """ cols = collections.defaultdict(list) q = [(root, 0)] while q: cur_cols = collections.defaultdict(list) for node, col in q: cur_cols[col].append(node.val) for c in cur_cols.keys(): cols[c].extend(sorted(cur_cols[c])) new_q = [] for node, col in q: if node.left is not None: new_q.append((node.left, col - 1)) if node.right is not None: new_q.append((node.right, col + 1)) q = new_q return [cols[c] for c in sorted(cols.keys())]