Tap here to switch tabs
Problem
Submissions
Solution

Solution: Vertical Order Traversal of a Binary Tree

Statement

Naive approach

The naive approach would be traversing the tree to get the maximum and minimum horizontal distance of the nodes from the root. Once we have these numbers, we can traverse over the tree again for each distance in the range [maximum, minimum] and return the nodes respectively.

The time complexity of the above algorithm is O(n2)O(n^2), where nn is the number of nodes. The space complexity is O(n)O(n).

Optimized approach using tree breadth-first search

Since we’re dealing with a binary tree, the approach that comes to mind is either depth-first search (DFS) or breadth-first search (BFS), which are both viable options. We will select BFS to solve this problem. Using BFS, we can assign the column1column − 1 ...

Tap here to switch tabs
Problem
Submissions
Solution

Solution: Vertical Order Traversal of a Binary Tree

Statement

Naive approach

The naive approach would be traversing the tree to get the maximum and minimum horizontal distance of the nodes from the root. Once we have these numbers, we can traverse over the tree again for each distance in the range [maximum, minimum] and return the nodes respectively.

The time complexity of the above algorithm is O(n2)O(n^2), where nn is the number of nodes. The space complexity is O(n)O(n).

Optimized approach using tree breadth-first search

Since we’re dealing with a binary tree, the approach that comes to mind is either depth-first search (DFS) or breadth-first search (BFS), which are both viable options. We will select BFS to solve this problem. Using BFS, we can assign the column1column − 1 ...