Recursive in-order traversal for Tree Vertical Scan.
但是由于左优先右,可能导致 上方的node 比 下方的node 更晚被 扫到。所以有一些test case 会 fail.
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution(object):
def verticalOrder(self, root):
"""
:type root: TreeNode
:rtype: List[List[int]]
"""
if root is None:
return []
collect = {}
index = 0
verticalTraversal(root, index, collect)
res = []
for idx in range(min(collect.keys()), max(collect.keys())+1):
res.append(collect[idx])
return res
def verticalTraversal(root, index, collect):
if index not in collect:
collect[index] = [root.val]
else:
collect[index].append(root.val)
if root.left is not None:
verticalTraversal(root.left, index-1, collect)
if root.right is not None:
verticalTraversal(root.right, index+1, collect)
为了达到 从上到下,从左到右的 要求,可以使用 level traversal。中间遇到个小问题,index 怎么随着 node.left; node.right 进行传递? 用到了 tuple, (index, node) --> Tuple 基本上就是 简单的 data buddling 的方法,和class 类似,在一些 需要 简单的 data coupling/bundling 的情况下用到。
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution(object):
def verticalOrder(self, root):
"""
:type root: TreeNode
:rtype: List[List[int]]
"""
res = []
if root is None:
return res
collect_map = level_traversal(root)
for index in sorted(collect_map.keys()):
res.append(collect_map[index])
return res
from collections import deque
def level_traversal(root):
# index: list<int>
collect_map = {}
if root is None:
return [collect_map]
index = 0
queue = deque([(index, root)])
while queue:
curr = queue.popleft()
curr_index = curr[0]
curr_node = curr[1]
# get info from current node
if curr_index in collect_map.keys():
collect_map[curr_index].append(curr_node.val)
else:
collect_map[curr_index] = list([curr_node.val])
# add node from the level below
if curr_node.left is not None:
queue.append((curr_index-1, curr_node.left))
if curr_node.right is not None:
queue.append((curr_index+1, curr_node.right))
return collect_map
有个更加简单 clean 的代码,也用到 tuple 来解决问题
优点:
1. 把 我在主函数里用到的逻辑 打包放在 函数里,这样确实更加清晰。
2. 用了 broadcast 函数,看上去高级。确实对于可以 emurable 的结构都可以 尝试用 broadcast.
优点:
1. 有些语法糖,看上去 fancy,但其实可读性不行。
def verticalOrder(self, root):
cols = collections.defaultdict(list)
queue = collections.deque([(root, 0)])
while queue:
node, i = queue.popleft()
if node:
cols[i].append(node.val)
queue += (node.left, i - 1), (node.right, i + 1)
return [cols[i] for i in sorted(cols)]