原题
https://leetcode.com/problems/binary-tree-vertical-order-traversal/
解法
BFS + 字典. 我们构造字典, 储存列值和对应的节点值, 设根节点的列值为0, 那么它的左节点的列是-1, 右节点的列是1, 然后使用广度优先搜索, 将每层的节点和对应的列数放入q, 然后更新字典. 最后我们将字典的键升序排列, 求对应的值即可.
Time: 2* O(n)
Space: O(1)
代码
# 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 verticalOrder(self, root):
"""
:type root: TreeNode
:rtype: List[List[int]]
"""
# base case
if not root: return []
cols = collections.defaultdict(list)
q = [(root, 0)]
while q:
for node, col in q:
cols[col].append(node.val)
new_q = []
for node, col in q:
if node.left:
new_q.append((node.left, col-1))
if node.right:
new_q.append((node.right, col+1))
q = new_q
return [cols[c] for c in sorted(cols.keys())]