🌳

Vertical Order Traversal in a Binary Tree

Jun 20, 2024

Vertical Order Traversal in a Binary Tree

Introduction

  • Thank Reliable for sponsoring the three-series video.
  • Problem: How to solve Vertical Order Traversal in a Binary Tree.
  • Approach: Draw vertical lines in the binary tree; each line represents a vertical order.

Vertical Order Concept

  • Vertical lines drawn in a binary tree from top to bottom.
  • If nodes overlap vertically, write the smaller value first.
  • Write vertical order from left to right and each vertical from top to bottom.
  • Return a vector of vectors or a list of lists describing vertical order traversal.

Approach to Solve the Problem

  • Consider verticals as points on the x-axis (e.g., 0, -1, -2, +1, +2).
  • Assign levels to nodes (e.g., root is level 0, left child level 1, etc.).
  • Traverse nodes level-wise and map them to verticals.

Data Structures

Mapping Verticals and Levels

  • Use a queue for level-order traversal.
  • Use a map to store nodes based on their vertical and level positions.
  • In C++: map<int, map<int, multiset<int>>>.
  • In Java: TreeMap<Integer, TreeMap<Integer, PriorityQueue<Integer>>>.

Level Order Traversal Using Queue

  • Store the node, vertical, and level in the queue.
  • For each node, calculate left and right child positions and push them into the queue.
  • Left Child: vertical = current - 1, level = current + 1.
  • Right Child: vertical = current + 1, level = current + 1.
  • Insert nodes into the data structure as they are dequeued.

Code Explanation

C++ Code

  • Initialize the queue with root, 0, 0.
  • Use level-order traversal to populate the map.
  • Traverse the map to construct the final result.

Java Code

  • Use a tuple to track the node, vertical, and level.
  • Level-order traversal using a queue (similar to C++ approach).
  • Construct results by traversing the map.

Time and Space Complexity

  • Time Complexity: O(N log N) due to priority queue or multiset operations.
  • Space Complexity: O(N) to store nodes in the data structures.

Homework

  • Implement the solution using in-order or post-order traversal and share in the comments.

Conclusion

  • Video aims to make the concept and coding easy to understand.
  • Encouragement to like, comment, and subscribe for more content.