651. Binary Tree Vertical Order Traversal
https://www.lintcode.com/problem/binary-tree-vertical-order-traversal/description
这道题本质上还是一个层序遍历,只不过增加了一个纵向列的信息。每当有左孩子,添加当前列-1的列信息;每当有右孩子,添加当前列+1的列信息。最后将字典中,从min到max的所有列按顺序取出来即可。
代码如下:
"""
Definition of TreeNode:
class TreeNode:
def __init__(self, val):
self.val = val
self.left, self.right = None, None
"""
class TreeColumnNode:
def __init__(self, node, col):
self.node = node
self.col = col
class Solution:
"""
@param root: the root of tree
@return: the vertical order traversal
"""
def verticalOrder(self, root):
res = []
if not root:
return res
queue = [TreeColumnNode(root, 0)]
cur_num, nxt_num = 1, 0
min_value, max_value = 0, 0
res_dict = {}
while queue:
cur_node = queue.pop()
cur_num -= 1
if cur_node.col in res_dict:
res_dict[cur_node.col].append(cur_node.node.val)
else:
res_dict[cur_node.col] = [cur_node.node.val]
if cur_node.node.left:
queue.insert(0, TreeColumnNode(cur_node.node.left, cur_node.col - 1))
nxt_num += 1
min_value = min(min_value, cur_node.col - 1)
if cur_node.node.right:
queue.insert(0, TreeColumnNode(cur_node.node.right, cur_node.col + 1))
nxt_num += 1
max_value = max(max_value, cur_node.col + 1)
if cur_num == 0:
cur_num = nxt_num
nxt_num = 0
for i in range(min_value, max_value + 1):
res.append(res_dict[i])
return res
网友评论