</> MAANG.io
coding interview ยท 101

Foundations

Master coding interviews with comprehensive coverage of data structures, algorithms, and problem-solving techniques. Progress from fundamentals to advanced topics with expertly curated content.

0/255 solved 0% complete

Special Traversals

What is this?

A few tree problems don't care about the usual visiting orders at all โ€” they want the output arranged by where things sit in space, like reading a tree column by column. The trick is to give every node a pair of coordinates (its row and column) as you walk through, completely ignoring the tree's shape. Once each node carries a position, the whole problem turns into something simple: sort the nodes by their coordinates.

flowchart TD A["Walk the tree"] --> B["Give each node a row and column"] B --> C["Collect all the positions"] C --> D["Sort by column then row"] D --> E["Read off the answer"]

๐Ÿ’ก Fun fact: This is the same idea behind how a spreadsheet or a screen lays things out โ€” every cell or pixel has a coordinate, so arranging them is just sorting by position.

๐Ÿ”“ The 1 problem in this chapter is free. Sign in with Google or Microsoft to start solving.


Core idea: Some tree problems don't ask for inorder/preorder/level order at all โ€” they ask for an output defined by position (columns, rows, diagonals). The trick is to stop thinking about tree shape and assign every node a coordinate, then the answer is just a multi-key sort of those coordinates.


Coordinates over shape

Coordinate rules: root = (row 0, col 0), left child = (row+1, col-1), right child = (row+1, col+1); then group by col and sort within col by (row, value)

Once each node carries (row, col), the tree's branching is irrelevant โ€” you collect tuples and sort. Getting the tie-break order exactly right (column, then row, then value) is where most solutions break.


The problem

Special traversal technique (coordinates + sort) mapped to the problem Vertical Order Traversal

  • Vertical Order Traversal of a Binary Tree โ€” assign (row, col), group by column left-to-right, and within a column sort by row then by value for same-cell collisions.

Key takeaways

  • Give nodes coordinates โ€” a geometric output contract becomes a sort.
  • Mind the tie-break โ€” column, then row, then value; the value tie-break is the classic bug.
  • Tree shape stops mattering once every node has a position.
  • Why interviewers love it: it checks whether you can translate an unusual output spec into a precise comparator.

Problem: Vertical Order Traversal of a Binary Tree.

Sign in to MAANG.io

Use your Google or Microsoft account โ€” no password to remember.

Continue with Google Continue with Microsoft

Please accept the terms above to continue.