In this video, we will explore the vertical traversal of a binary tree. The goal is to print the nodes of the tree in vertical columns, starting from the leftmost level to the rightmost level. If multiple nodes fall on the same vertical line, they will be printed in the order of their level traversal.
The first approach we will cover is a brute force method, where we first calculate the minimum and maximum horizontal distances (HD) from the root node. We then iterate over each vertical line, traversing the tree and collecting the nodes that fall on that line. This method has a time complexity of O(n^2) due to the multiple traversals, and uses O(n) space.
The more efficient approach uses Depth-First Search (DFS) and a hashmap. We start at the root with a horizontal distance (HD) of 0. For each left child, we decrement the HD, and for each right child, we increment the HD. As we traverse, we store each node’s value in a hashmap, with the HD as the key. After traversing the entire tree, we collect the nodes in increasing order of HD to produce the vertical order. This approach runs in O(n) time and uses O(n) space, making it much more efficient. Watch the video to understand how both methods work in detail.
For more details, please go through - Vertical Traversal of a Binary Tree