bugfree Icon
interview-course
interview-course
interview-course
interview-course
interview-course
interview-course
interview-course
interview-course

Leetcode Problem 987. Vertical Order Traversal of a Binary Tree

987. Vertical Order Traversal of a Binary Tree

Leetcode Solutions

BFS with Global Sorting

  1. Initialize a list to store tuples of the form (column index, row index, node value).
  2. Perform a BFS traversal starting from the root node, which is at column index 0 and row index 0.
  3. For each node visited, add a tuple to the list with the current column index, row index, and node value.
  4. For each child node, update the column index (decrement for left child, increment for right child) and increment the row index before adding it to the BFS queue.
  5. After the BFS traversal, sort the list of tuples first by column index, then by row index, and finally by node value if necessary.
  6. Iterate through the sorted list and group nodes by their column index to form the final result.
  7. Return the grouped list as the vertical order traversal.
UML Thumbnail

DFS with Partition Sorting

Ask Question

Programming Language
image/screenshot of info(optional)
Full Screen
Loading...

Suggested Answer

Answer
Full Screen
Copy Answer Code
Loading...