651 · 二叉树垂直遍历
描述
给定二叉树,返回其节点值的垂直遍历顺序。 (即逐列从上到下)。如果两个节点在同一行和同一列中,则顺序应 从左到右。
Example1
Inpurt: {3,9,20,#,#,15,7} Output: [[9],[3,15],[20],[7]] Explanation: 3 /\ / \ 9 20 /\ / \ 15 7
Example2
Input: {3,9,8,4,0,1,7} Output: [[4],[9],[3,0,1],[8],[7]] Explanation: 3 /\ / \ 9 8 /\ /\ / \/ \ 4 01 7
法 1 BFS
思路
先完整的遍历一遍二叉树,遍历的过程用 字典记录各节点的值和位置信息。然后再根据记录的位置信息来生成所要的答案
题解
from typing import ( List, ) from lintcode import ( TreeNode, ) """ Definition of TreeNode: class TreeNode: def __init__(self, val): self.val = val self.left, self.right = None, None """ class Solution: """ @param root: the root of tree @return: the vertical order traversal """ def vertical_order(self, root: TreeNode) -> List[List[int]]: if root is None: return [] # 记录各节点的位置信息 position = collections.defaultdict(list) queue = collections.deque() queue.append((root,0)) while queue: cur_node, cur_pos = queue.popleft() position[cur_pos].append(cur_node.val) if cur_node.left: queue.append((cur_node.left, cur_pos-1)) if cur_node.right: queue.append((cur_node.right, cur_pos+1)) min_idx = min(position.keys()) res = [] while position[min_idx]: res += [position[min_idx]] min_idx += 1 return res
因为对于同一列的节点需要按照从上到下的顺便存放,采用dfs的话,容易错位,故还需要保存深度信息,即行值,有点繁琐,不采用