Top View of BT

Binary Trees FAQs Medium
  • Fun Fact: The underlying concept of this problem, which is traversing through a binary tree, is extensively used in databases as well as file systems
  • For instance, the B-tree structure, a type of binary tree, allows for efficient insertion, deletion and search operations
  • This is especially beneficial for databases and file systems where data is large and needs to be stored on the hard drive
  • In cases like these, reducing the number of disk access during operations is crucial for the overall performance
  • So, understanding how to traverse binary trees isn't just restricted to coding puzzles, but has very tangible real-world applications in software development!

Given the root of a binary tree, return the top view of the binary tree.


Top view of a binary tree is the set of nodes visible when the tree is viewed from the top. Return nodes from the leftmost node to the rightmost node. Also if 2 nodes are outside the shadow of the tree and are at the same position then consider the left ones only(i.e. leftmost). 

Examples:

Input : root = [1, 2, 3, 4, 5, 6, 7]

Output : [4, 2, 1, 3, 7]

Explanation :

Input : root = [10, 20, 30, 40, 60, 90, 100]

Output : [40, 20, 10, 30, 100]

Explanation :

Input : root = [5, 1, 2, 8, null, 4, 5, null, 6]

Constraints

  • 1 <= Number of Nodes <= 104
  • -103 <= Node.val <= 103

Hints

  • Use a queue of tuples (node, horizontal_distance), starting with (root, 0). Process each node level by level, ensuring that we encounter nodes in top-to-bottom order.
  • Use a hashmap (top_nodes) where: Key: Horizontal Distance (HD). Value: First node encountered at that HD. If an HD is encountered for the first time, store the node’s value.

Company Tags

AMD NVIDIA Splunk Zomato Medtronic Twilio Instacart Unity Technologies Zoho Pinterest Flipkart Epic Games IBM Cloudflare eBay Seagate Technology Zynga Bloomberg Freshworks Riot Games Optum JPMorgan Chase Red Hat Reddit OYO Rooms Google Microsoft Amazon Meta Apple Netflix Adobe