Bird
Raised Fist0
DSA Typescriptprogramming~15 mins

Vertical Order Traversal of Binary Tree in DSA Typescript - Deep Dive

Choose your learning style10 modes available
Overview - Vertical Order Traversal of Binary Tree
What is it?
Vertical Order Traversal of a Binary Tree is a way to visit all nodes column by column from left to right. Imagine drawing vertical lines through the tree and collecting nodes that fall on the same line. We then print these nodes from top to bottom for each vertical line. This helps us see the tree from a vertical perspective instead of the usual horizontal level order.
Why it matters
Without vertical order traversal, we miss an important way to understand the structure of a tree. It helps in problems where the relative horizontal position of nodes matters, like printing a tree as seen from the side or solving layout problems. Without it, we would only see nodes level by level, losing the spatial relationship between nodes on the same vertical line.
Where it fits
Before learning this, you should understand basic binary trees and level order traversal. After mastering vertical order traversal, you can explore related concepts like top view, bottom view of trees, and horizontal distance based tree problems.
Mental Model
Core Idea
Group tree nodes by their horizontal distance from the root and print each group from top to bottom, moving from leftmost to rightmost group.
Think of it like...
Imagine standing in front of a tall bookshelf with many shelves (levels) and columns. Vertical order traversal is like looking at the bookshelf column by column from left to right, reading all books on each shelf in that column from top to bottom.
        (root)
          1
         / \
        2   3
       / \   \
      4   5   6

Horizontal distances:
 -2: 4
 -1: 2
  0: 1,5
  1: 3
  2: 6

Vertical order groups:
HD=-2: 4
HD=-1: 2
HD=0: 1,5
HD=1: 3
HD=2: 6

Printed left to right:
4 -> 2 -> 1 -> 5 -> 3 -> 6
Build-Up - 7 Steps
1
FoundationUnderstanding Binary Tree Structure
πŸ€”
Concept: Learn what a binary tree is and how nodes connect with left and right children.
A binary tree is a structure where each node has up to two children: left and right. The top node is called the root. Each child can also have its own children, forming levels. For example, node 1 is root, nodes 2 and 3 are its children, and so on.
Result
You can visualize and identify nodes and their children in a tree.
Understanding the tree structure is essential because vertical order traversal depends on node positions relative to the root.
2
FoundationHorizontal Distance Concept
πŸ€”
Concept: Introduce horizontal distance (HD) as a way to measure node position relative to root.
Assign the root node a horizontal distance of 0. For any node, its left child has HD = parent's HD - 1, and right child has HD = parent's HD + 1. This helps group nodes vertically.
Result
Each node has a number representing its vertical column position.
Using horizontal distance lets us group nodes by vertical lines, which is the core of vertical order traversal.
3
IntermediateCollecting Nodes by Horizontal Distance
πŸ€”Before reading on: do you think nodes with the same horizontal distance always appear at the same level? Commit to yes or no.
Concept: Use a map to collect nodes sharing the same horizontal distance during traversal.
Traverse the tree (e.g., using BFS). For each node, record its HD and add it to a map where keys are HDs and values are lists of nodes. This groups nodes vertically.
Result
A map like { -2: [4], -1: [2], 0: [1,5], 1: [3], 2: [6] } is created.
Grouping nodes by HD during traversal organizes the tree vertically, enabling easy printing from left to right.
4
IntermediateOrdering Nodes Top to Bottom Within Columns
πŸ€”Before reading on: do you think BFS or DFS is better to maintain top-to-bottom order in vertical groups? Commit to your answer.
Concept: Use level order traversal (BFS) to ensure nodes are added top to bottom within each vertical group.
BFS visits nodes level by level, so when adding nodes to HD groups, they naturally appear from top to bottom. DFS might mix levels and lose this order.
Result
Nodes in each HD group are ordered from top to bottom, e.g., HD=0 group is [1,5].
Choosing BFS preserves the vertical order's top-to-bottom requirement without extra sorting.
5
IntermediateSorting Horizontal Distances for Output
πŸ€”
Concept: After collecting nodes, sort the horizontal distances to print columns from left to right.
Extract all HD keys from the map, sort them ascending, then print nodes in each group in that order.
Result
Output order is columns from leftmost HD to rightmost HD.
Sorting HD keys ensures the vertical columns are printed in the correct left-to-right sequence.
6
AdvancedHandling Nodes at Same Position with Tie-breakers
πŸ€”Before reading on: do you think nodes at the same HD and level should be printed in any order or sorted by value? Commit to your answer.
Concept: When multiple nodes share the same HD and level, sort them by their values to maintain a consistent order.
Use a data structure that stores nodes with their HD and level. After traversal, sort nodes first by HD, then by level, then by node value to break ties.
Result
Nodes at the same position are printed in ascending order of their values.
Tie-breaking by node value ensures deterministic output, important for consistent results in tests and applications.
7
ExpertOptimizing with Balanced Data Structures
πŸ€”Before reading on: do you think a simple map and list suffice for large trees or a balanced tree/map is better? Commit to your answer.
Concept: Use balanced trees or ordered maps to store nodes by HD and level efficiently for large inputs.
Instead of unsorted maps, use data structures like TreeMap (in Java) or SortedMap to keep HD keys sorted automatically. Also, use priority queues to sort nodes at the same HD and level by value during insertion.
Result
Efficient insertion and retrieval maintain order without costly sorting after traversal.
Using balanced data structures improves performance and scalability for large trees in production.
Under the Hood
Vertical order traversal uses a breadth-first search (BFS) to visit nodes level by level while tracking each node's horizontal distance (HD) from the root. Nodes are stored in a map keyed by HD. Internally, BFS uses a queue to process nodes in order, and each node's HD is calculated by adding or subtracting 1 from its parent's HD. After traversal, the map keys are sorted to print nodes from leftmost to rightmost vertical lines. Tie-breakers use node values to order nodes sharing the same HD and level.
Why designed this way?
This method was designed to capture the spatial layout of a tree as seen vertically. Using BFS ensures nodes are processed top to bottom, preserving natural tree levels. Tracking HD allows grouping nodes by vertical lines. Alternatives like DFS do not guarantee top-to-bottom order, and sorting after traversal can be costly. The design balances clarity, correctness, and efficiency.
β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚    Queue      β”‚
β”‚  (BFS order)  β”‚
β””β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”˜
       β”‚
       β–Ό
β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”       β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚  Node + HD    │──────▢│  Map: HD ->   β”‚
β”‚ (value, HD)   β”‚       β”‚  list of nodesβ”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜       β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
       β”‚                       β–²
       β–Ό                       β”‚
β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”       β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚  Add children │◀──────│  Calculate HD β”‚
β”‚  with HD Β± 1  β”‚       β”‚  for children β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜       β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
Myth Busters - 3 Common Misconceptions
Quick: Does DFS traversal guarantee nodes are printed top to bottom in vertical order? Commit yes or no.
Common Belief:DFS traversal is fine for vertical order because it visits all nodes.
Tap to reveal reality
Reality:DFS does not guarantee top-to-bottom order within vertical columns because it can go deep on one branch before visiting nodes at higher levels on another branch.
Why it matters:Using DFS can produce incorrect vertical order output, mixing node levels and confusing the vertical structure.
Quick: Do nodes with the same horizontal distance always appear at the same level? Commit yes or no.
Common Belief:Nodes sharing the same horizontal distance are always on the same level.
Tap to reveal reality
Reality:Nodes with the same horizontal distance can be on different levels (depths) in the tree.
Why it matters:Assuming same level causes wrong grouping and ordering, leading to incorrect vertical order traversal.
Quick: Is sorting nodes by value necessary when multiple nodes share the same HD and level? Commit yes or no.
Common Belief:Sorting nodes by value at the same position is not needed; any order works.
Tap to reveal reality
Reality:Sorting by node value is needed to produce consistent and deterministic output, especially in tests or when multiple nodes overlap.
Why it matters:Without sorting, output can vary between runs or implementations, causing confusion and test failures.
Expert Zone
1
When nodes share the same HD and level, sorting by node value is a subtle but crucial detail for deterministic output.
2
Using BFS with a queue naturally preserves top-to-bottom order, avoiding extra sorting steps that DFS would require.
3
Balanced data structures like ordered maps or priority queues optimize performance for large trees by maintaining sorted order during insertion.
When NOT to use
Vertical order traversal is not suitable when only level order or simple preorder/postorder traversals are needed. For problems focusing on subtree properties or path sums, other traversals are better. Also, if the tree is very large and memory is limited, vertical order traversal may be costly due to storing all nodes by HD.
Production Patterns
In production, vertical order traversal is used in graphical tree layout engines, printing trees in human-readable formats, and solving spatial problems like skyline views. It is also used in coding interviews to test understanding of BFS, maps, and sorting tie-breakers.
Connections
Breadth-First Search (BFS)
Vertical order traversal builds on BFS by adding horizontal distance tracking.
Understanding BFS is key because it naturally visits nodes level by level, which vertical order traversal relies on to maintain top-to-bottom order.
Top View of Binary Tree
Vertical order traversal groups nodes by vertical lines, while top view selects only the topmost node per vertical line.
Knowing vertical order traversal helps understand how to extract views like top or bottom view by filtering nodes in each vertical group.
Geographic Mapping Systems
Both use coordinate systems to group and order elements spatially.
Just like vertical order traversal groups nodes by horizontal distance, mapping systems group locations by longitude and latitude, showing how spatial grouping is a universal concept.
Common Pitfalls
#1Using DFS instead of BFS causes wrong vertical order output.
Wrong approach:function verticalOrderDFS(root) { // DFS traversal // Visit left, then right recursively // Add nodes to map by HD }
Correct approach:function verticalOrderBFS(root) { // Use queue for BFS // Track HD for each node // Add nodes to map by HD in BFS order }
Root cause:DFS does not guarantee visiting nodes top to bottom, mixing levels in vertical groups.
#2Not sorting horizontal distances before output.
Wrong approach:for (const hd in map) { print(map[hd]); }
Correct approach:const sortedHDs = Object.keys(map).map(Number).sort((a,b) => a - b); for (const hd of sortedHDs) { print(map[hd]); }
Root cause:Object keys are unordered; sorting ensures left-to-right vertical order.
#3Ignoring tie-breakers for nodes at same HD and level.
Wrong approach:Store nodes in list without sorting by value when HD and level are equal.
Correct approach:Sort nodes by value when HD and level are equal before printing.
Root cause:Without tie-breakers, output order is inconsistent and non-deterministic.
Key Takeaways
Vertical order traversal groups nodes by their horizontal distance from the root, printing columns from left to right.
Breadth-first search (BFS) is essential to maintain top-to-bottom order within each vertical group.
Tracking horizontal distance and level allows correct grouping and ordering of nodes.
Sorting horizontal distances and tie-breaking nodes at the same position by value ensures consistent output.
Using balanced data structures optimizes performance for large trees and complex tie-break scenarios.

Practice

(1/5)
1. What does Vertical Order Traversal of a binary tree mean?
easy
A. Nodes are grouped by their vertical columns from left to right
B. Nodes are visited level by level from top to bottom
C. Nodes are visited in preorder (root, left, right)
D. Nodes are visited in inorder (left, root, right)

Solution

  1. Step 1: Understand vertical columns in a tree

    Vertical order groups nodes by their horizontal distance from the root, called columns.
  2. Step 2: Define vertical order traversal

    Nodes in the same vertical column are collected and output from leftmost to rightmost column.
  3. Final Answer:

    Nodes are grouped by their vertical columns from left to right -> Option A
  4. Quick Check:

    Vertical order = group by columns [OK]
Hint: Think columns from left to right, not levels or preorder [OK]
Common Mistakes:
  • Confusing vertical order with level order traversal
  • Thinking vertical order is preorder or inorder traversal
  • Ignoring horizontal distance concept
2. Which TypeScript data structure is best to store nodes by their vertical column during vertical order traversal?
easy
A. Map
B. Set<number>
C. Array<number>
D. string[]

Solution

  1. Step 1: Identify need to map columns to nodes

    We need to store nodes grouped by their column index, so a mapping from column number to list of nodes is required.
  2. Step 2: Choose appropriate TypeScript structure

    A Map with keys as column numbers and values as arrays of node values fits perfectly.
  3. Final Answer:

    Map<number, number[]> -> Option A
  4. Quick Check:

    Map column to node list = Map<number, number[]> [OK]
Hint: Use Map to link column numbers to node arrays [OK]
Common Mistakes:
  • Using Set which does not store duplicates or order
  • Using plain arrays without column keys
  • Using string arrays which don't map columns
3. Given this TypeScript code for vertical order traversal, what is the output?
class TreeNode {
  val: number;
  left: TreeNode | null;
  right: TreeNode | null;
  constructor(val: number) {
    this.val = val;
    this.left = null;
    this.right = null;
  }
}

const root = new TreeNode(1);
root.left = new TreeNode(2);
root.right = new TreeNode(3);
root.left.left = new TreeNode(4);
root.left.right = new TreeNode(5);
root.right.left = new TreeNode(6);
root.right.right = new TreeNode(7);

function verticalOrder(root: TreeNode | null): number[][] {
  if (!root) return [];
  const map = new Map();
  const queue: [TreeNode, number][] = [[root, 0]];
  while (queue.length) {
    const [node, col] = queue.shift()!;
    if (!map.has(col)) map.set(col, []);
    map.get(col)!.push(node.val);
    if (node.left) queue.push([node.left, col - 1]);
    if (node.right) queue.push([node.right, col + 1]);
  }
  return Array.from(map.entries())
    .sort((a, b) => a[0] - b[0])
    .map(entry => entry[1]);
}

console.log(verticalOrder(root));
medium
A. [[7], [3], [1, 5, 6], [2], [4]]
B. [[4], [2], [1, 5, 6], [3], [7]]
C. [[1], [2, 3], [4, 5, 6, 7]]
D. [[4], [2, 5], [1, 6], [3, 7]]

Solution

  1. Step 1: Assign columns to nodes during BFS

    Root (1) at col 0; left child (2) at -1; right child (3) at +1; and so on. Nodes grouped by columns: - -2: 4 - -1: 2 - 0: 1, 5, 6 - 1: 3 - 2: 7
  2. Step 2: Sort columns and output node lists

    Sorted columns from left to right: -2, -1, 0, 1, 2. Output arrays accordingly.
  3. Final Answer:

    [[4], [2], [1, 5, 6], [3], [7]] -> Option B
  4. Quick Check:

    Column grouping matches output D [OK]
Hint: Track column indices during BFS, then sort keys [OK]
Common Mistakes:
  • Mixing up column indices for left/right children
  • Not sorting columns before output
  • Using DFS instead of BFS causing wrong order
4. The following TypeScript code for vertical order traversal has a bug. What is the bug?
function verticalOrder(root: TreeNode | null): number[][] {
  if (!root) return [];
  const map = new Map();
  const queue: [TreeNode, number][] = [[root, 0]];
  while (queue.length) {
    const [node, col] = queue.pop()!;
    if (!map.has(col)) map.set(col, []);
    map.get(col)!.push(node.val);
    if (node.left) queue.push([node.left, col - 1]);
    if (node.right) queue.push([node.right, col + 1]);
  }
  return Array.from(map.entries())
    .sort((a, b) => a[0] - b[0])
    .map(entry => entry[1]);
}
medium
A. map.get(col) returns undefined
B. Missing check for null root
C. Using queue.pop() causes DFS instead of BFS traversal
D. Sorting map entries is incorrect

Solution

  1. Step 1: Identify queue operation used

    The code uses queue.pop(), which removes the last element, making it a stack (DFS) behavior.
  2. Step 2: Explain impact on vertical order traversal

    Vertical order requires BFS (level order) to maintain correct node order per column. Using pop() breaks this order.
  3. Final Answer:

    Using queue.pop() causes DFS instead of BFS traversal -> Option C
  4. Quick Check:

    pop() = DFS, need shift() for BFS [OK]
Hint: Use shift() for BFS queue, not pop() [OK]
Common Mistakes:
  • Confusing pop() with shift() in queue
  • Ignoring traversal order effect on output
  • Assuming map.get always returns array without check
5. You want to modify vertical order traversal to sort nodes within the same column by their row (depth) and then by value ascending. Which approach is best?
hard
A. Traverse tree using DFS only and collect nodes in order
B. Use a Set per column to avoid duplicates
C. Sort nodes globally after traversal ignoring columns
D. Store nodes as tuples (row, value) per column and sort before output

Solution

  1. Step 1: Understand sorting requirement within columns

    Nodes in the same column must be sorted first by their row (depth), then by value ascending.
  2. Step 2: Choose data structure to store row and value

    Store tuples (row, value) for each node in the column map, then sort these tuples before output.
  3. Step 3: Explain why other options fail

    Set ignores duplicates and order; DFS alone doesn't guarantee order; global sort ignores column grouping.
  4. Final Answer:

    Store nodes as tuples (row, value) per column and sort before output -> Option D
  5. Quick Check:

    Sort by row and value per column = store tuples and sort [OK]
Hint: Keep (row, value) pairs per column, then sort [OK]
Common Mistakes:
  • Using Set which loses order and duplicates
  • Relying on DFS without tracking rows
  • Sorting all nodes ignoring column grouping
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard