Binary Tree Vertical Order Traversal
Question (LC.314)
Given a binary tree, return the vertical order traversal of its nodes' values.
Example
I: root = [3,9,20,null,null,15,7]
O: [[9], [3, 15], [20], [7]]
I: root = [3,9,8,4,0,1,7,null,null,null,2,5]
O: [[4], [9,5], [3,0,1], [8,2], [7]]Analysis
The key of unlocking this question is to understand the definition of vertical order.
i.e. from top to bottom, column by column
if two nodes are in the same row and column, the order should be from left to right.
There are two conditions in this ordering, rows and columns. I have missed the rows part when I first read this question.
For example, [3,9,8,4,0,1,7,null,null,null,2,5] has the following diagram.

Which can be represented in a matrix like this
row/col
-2
-1
0
1
2
0
3
1
9
8
2
4
0,1
7
3
5
2
A corner case without row key with DFS is [8, 2] will be [2, 8]. BFS gets row key sort of for free.
DFS Code
time O(nlogn)
space O(n)
BFS Code
time O(nlogn)
space O(n)
Last updated