314. Binary Tree Vertical Order Traversal(树bfs)

bfs dfs

Given a binary tree, return the vertical order traversal of its nodes' values. (ie, from top to bottom, column by column).

If two nodes are in the same row and column, the order should be fromleft to right.

Example

Given binary tree{3,9,20,#,#,15,7}

   3
  /\
 /  \
 9  20
    /\
   /  \
  15   7

Return its vertical order traversal as: [[9],[3,15],[20],[7]]

Given binary tree{3,9,8,4,0,1,7}

     3
    /\
   /  \
   9   8
  /\  /\
 /  \/  \
 4  01   7

Return its vertical order traversal as: [[4],[9],[3,0,1],[8],[7]]

分析

如果是要求层顺序,使用bfs,如果要求root和l,r顺序,考虑pre in post

这题不知道为什么dfs不行,可能因为顺序?

因为要求行列都顺序,BFS天然保留了行顺序,只需要考虑COL顺序

但DFS需要加入额外的ROW追踪。

DFS

coldict可以用负数做Key和排序, 必须追踪ROW, 因为row也需要排序输出, 如果没有row #, 无法给行排序。

Last updated

Was this helpful?