JobHoppoer-314. Binary Tree Vertical Order Traversal

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)]

Loading...

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值