Bird
Raised Fist0
DSA Goprogramming

Vertical Order Traversal of Binary Tree in DSA Go

Choose your learning style10 modes available
Mental Model
We group tree nodes by their vertical columns from left to right, and within each column, nodes are ordered top to bottom.
Analogy: Imagine standing in front of a tree and looking straight at it. You draw vertical lines through the tree. Nodes that fall on the same line are grouped together, like people standing in the same vertical queue.
      1
     / \
    2   3
   / \   \
  4   5   6

Columns:  -2  -1   0   1   2
Nodes:    4   2   1,5,6  3
Dry Run Walkthrough
Input: Binary tree: 1 / \ 2 3 / \ \ 4 5 6
Goal: Print nodes grouped by vertical columns from left to right, top to bottom within each column.
Step 1: Start at root node 1 with column 0
Column 0: [1]
Columns so far: {0: [1]}
Why: Root is the center column, so we assign it column 0
Step 2: Move to left child 2 with column -1
Column -1: [2]
Columns so far: {-1: [2], 0: [1]}
Why: Left child is one column to the left
Step 3: Move to left child 4 with column -2
Column -2: [4]
Columns so far: {-2: [4], -1: [2], 0: [1]}
Why: Left child again moves one column left
Step 4: Back to node 2, move to right child 5 with column 0
Column 0: [1,5]
Columns so far: {-2: [4], -1: [2], 0: [1,5]}
Why: Right child moves one column right from parent
Step 5: Back to root 1, move to right child 3 with column 1
Column 1: [3]
Columns so far: {-2: [4], -1: [2], 0: [1,5], 1: [3]}
Why: Right child moves one column right
Step 6: Move to right child 6 of node 3 with column 2
Column 2: [6]
Columns so far: {-2: [4], -1: [2], 0: [1,5], 1: [3], 2: [6]}
Why: Right child moves one column right
Result:
Vertical order traversal:
Column -2: 4
Column -1: 2
Column 0: 1 -> 5
Column 1: 3
Column 2: 6
Annotated Code
DSA Go
package main

import (
	"fmt"
)

type TreeNode struct {
	Val   int
	Left  *TreeNode
	Right *TreeNode
}

func verticalOrderTraversal(root *TreeNode) [][]int {
	if root == nil {
		return [][]int{}
	}

	// Map column index to list of node values
	columnTable := make(map[int][]int)
	// Queue for BFS: stores node and its column index
	type pair struct {
		node  *TreeNode
		col int
	}
	queue := []pair{{root, 0}}

	minCol, maxCol := 0, 0

	for len(queue) > 0 {
		p := queue[0]
		queue = queue[1:]

		node, col := p.node, p.col

		columnTable[col] = append(columnTable[col], node.Val) // add node to its column

		if node.Left != nil {
			queue = append(queue, pair{node.Left, col - 1}) // left child column -1
			if col-1 < minCol {
				minCol = col - 1
			}
		}

		if node.Right != nil {
			queue = append(queue, pair{node.Right, col + 1}) // right child column +1
			if col+1 > maxCol {
				maxCol = col + 1
			}
		}
	}

	result := [][]int{}
	for c := minCol; c <= maxCol; c++ {
		result = append(result, columnTable[c]) // collect columns left to right
	}
	return result
}

func main() {
	// Build tree:
	//      1
	//     / \
	//    2   3
	//   / \   \
	//  4   5   6

	n4 := &TreeNode{Val: 4}
	n5 := &TreeNode{Val: 5}
	n6 := &TreeNode{Val: 6}
	n2 := &TreeNode{Val: 2, Left: n4, Right: n5}
	n3 := &TreeNode{Val: 3, Right: n6}
	n1 := &TreeNode{Val: 1, Left: n2, Right: n3}

	res := verticalOrderTraversal(n1)
	for i, col := range res {
		fmt.Printf("Column %d: ", i+minCol)
		for j, val := range col {
			if j > 0 {
				fmt.Print(" -> ")
			}
			fmt.Print(val)
		}
		fmt.Println()
	}
}
queue := []pair{{root, 0}}
Initialize BFS queue with root at column 0
p := queue[0] queue = queue[1:]
Dequeue front node and its column
columnTable[col] = append(columnTable[col], node.Val)
Add current node value to its column group
if node.Left != nil { queue = append(queue, pair{node.Left, col - 1}) if col-1 < minCol { minCol = col - 1 } }
Add left child to queue with column one less, update min column
if node.Right != nil { queue = append(queue, pair{node.Right, col + 1}) if col+1 > maxCol { maxCol = col + 1 } }
Add right child to queue with column one more, update max column
for c := minCol; c <= maxCol; c++ { result = append(result, columnTable[c]) }
Collect columns from leftmost to rightmost
OutputSuccess
Column -2: 4 Column -1: 2 Column 0: 1 -> 5 Column 1: 3 Column 2: 6
Complexity Analysis
Time: O(n) because we visit each node once during BFS traversal
Space: O(n) for storing nodes in the queue and the column map
vs Alternative: Compared to DFS, BFS naturally processes nodes level by level, preserving top-to-bottom order within columns without extra sorting.
Edge Cases
Empty tree
Returns empty list since there are no nodes
DSA Go
if root == nil {
	return [][]int{}
}
Tree with only root node
Returns list with single column containing root value
DSA Go
queue := []pair{{root, 0}}
Tree with multiple nodes in same column and level
Nodes appear in order they are visited in BFS, preserving top-to-bottom order
DSA Go
columnTable[col] = append(columnTable[col], node.Val)
When to Use This Pattern
When a problem asks to group tree nodes by vertical lines or columns, use vertical order traversal with BFS and column indexing to preserve top-to-bottom order.
Common Mistakes
Mistake: Using DFS without sorting nodes by level causes incorrect top-to-bottom order in columns
Fix: Use BFS traversal to process nodes level by level, ensuring correct vertical order
Mistake: Not tracking min and max column indices leads to unordered output
Fix: Track minCol and maxCol during traversal to output columns from left to right
Summary
Groups binary tree nodes by vertical columns from left to right, preserving top-to-bottom order.
Use when you need to print or process nodes column-wise in a binary tree.
The key is to assign column indices during BFS and collect nodes per column in order.

Practice

(1/5)
1. What does vertical order traversal of a binary tree primarily group nodes by?
easy
A. Their parent node
B. Their depth level in the tree
C. Their value magnitude
D. Their horizontal distance from the root

Solution

  1. Step 1: Understand vertical order traversal concept

    Vertical order traversal groups nodes based on their horizontal distance from the root node, also called the vertical column.
  2. Step 2: Differentiate from other traversals

    Unlike level order which groups by depth, vertical order groups nodes that align vertically when the tree is viewed from top.
  3. Final Answer:

    Their horizontal distance from the root -> Option D
  4. Quick Check:

    Vertical order = horizontal distance grouping [OK]
Hint: Remember vertical means grouping by horizontal distance [OK]
Common Mistakes:
  • Confusing vertical order with level order traversal
  • Grouping by node values instead of position
  • Ignoring horizontal distance concept
2. Which Go data structure is best suited to store nodes grouped by their vertical column during vertical order traversal?
easy
A. map[string]int
B. []int
C. map[int][]int
D. [][]int

Solution

  1. Step 1: Identify grouping requirement

    We need to group nodes by their vertical column index, which is an integer key.
  2. Step 2: Choose suitable Go data structure

    A map with integer keys and slice of integers as values (map[int][]int) allows storing multiple node values per vertical column.
  3. Final Answer:

    map[int][]int -> Option C
  4. Quick Check:

    Use map[int][]int for vertical groups [OK]
Hint: Use map with int keys and slice values for grouping [OK]
Common Mistakes:
  • Using simple slices without keys
  • Using map with string keys unnecessarily
  • Choosing 2D slices without keys
3. Given the binary tree:
    1
   / \
  2   3
 /     \
4       5
What is the vertical order traversal output?
medium
A. [[4], [2], [1], [3], [5]]
B. [[4], [2], [1], [3, 5]]
C. [[4], [2, 1], [3, 5]]
D. [[1], [2, 3], [4, 5]]

Solution

  1. Step 1: Assign horizontal distances

    Root 1 is at 0, left child 2 at -1, left-left 4 at -2, right child 3 at +1, right-right 5 at +2.
  2. Step 2: Group nodes by horizontal distance

    At -2: [4], -1: [2], 0: [1], +1: [3], +2: [5].
  3. Final Answer:

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

    Group by horizontal distance = [[4], [2], [1], [3, 5]] [OK]
Hint: Label columns from left (-) to right (+) then group nodes [OK]
Common Mistakes:
  • Mixing node order inside same vertical column
  • Incorrect horizontal distance assignment
  • Ignoring multiple nodes in same vertical column
4. Consider this Go snippet for vertical order traversal:
func verticalOrder(root *Node) map[int][]int {
    result := make(map[int][]int)
    var dfs func(node *Node, hd int)
    dfs = func(node *Node, hd int) {
        if node == nil {
            return
        }
        result[hd] = append(result[hd], node.Val)
        dfs(node.Left, hd-1)
        dfs(node.Right, hd+1)
    }
    dfs(root, 0)
    return result
}
What is the main issue with this code?
medium
A. It uses DFS which may not preserve top-to-bottom order
B. It does not handle nil root input
C. It uses map instead of slice for result
D. It increments horizontal distance incorrectly

Solution

  1. Step 1: Analyze traversal method

    The code uses DFS which explores depth first, so nodes deeper may be added before shallower nodes in same vertical column.
  2. Step 2: Understand vertical order requirement

    Vertical order traversal requires nodes to be output top-to-bottom per vertical column, which BFS preserves but DFS may not.
  3. Final Answer:

    It uses DFS which may not preserve top-to-bottom order -> Option A
  4. Quick Check:

    DFS can misorder vertical nodes top-to-bottom [OK]
Hint: Use BFS, not DFS, to keep top-to-bottom order [OK]
Common Mistakes:
  • Assuming DFS preserves vertical order top-to-bottom
  • Ignoring traversal order impact on output
  • Thinking map usage causes order issues
5. You want to print the vertical order traversal of a binary tree sorted by vertical column from left to right and nodes top to bottom within each column. Which approach is best?
hard
A. Use BFS with a queue storing nodes and their horizontal distance, then sort keys
B. Use DFS with recursion and store nodes in map without sorting
C. Use inorder traversal and print nodes as visited
D. Use a stack to store nodes and print after traversal

Solution

  1. Step 1: Choose traversal preserving top-to-bottom order

    BFS visits nodes level by level, ensuring top nodes are processed before lower nodes in same vertical column.
  2. Step 2: Store nodes with horizontal distance and sort keys

    Use a queue to track nodes and their horizontal distance, store in map[int][]int, then output sorted by keys for left to right order.
  3. Final Answer:

    Use BFS with a queue storing nodes and their horizontal distance, then sort keys -> Option A
  4. Quick Check:

    BFS + sorting keys = correct vertical order traversal [OK]
Hint: BFS + map + sort keys for correct vertical order [OK]
Common Mistakes:
  • Using DFS which breaks top-to-bottom order
  • Not sorting map keys before printing
  • Using stack which reverses order
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