Right/Left View of BT

Binary Trees FAQs Medium
  • This programming problem is practically applied in database technologies that involve tree-based indexing like B-Trees or B+ Trees, commonly used in many SQL and NoSQL databases
  • For instance, MongoDB utilizes a variant of B-tree data structure for its indexes
  • Visibility from a certain perspective (here, it's from the right) can be used to optimize searches, traversals, or even distribution of nodes in parallel computing scenarios
  • Hence, understanding these kinds of problems is key to designing efficient data management or networking systems

Assuming standing on the right side of a binary tree and given its root, return the values of the nodes visible, arranged from top to bottom.

Examples:

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

Output : [1, 3, 4]

Explanation :

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

Output : [1, 3, 4]

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 to process nodes level by level, keeping track of their depth. At each level, store only the last node encountered in that level (i.e., the rightmost node). Process the right child first, then the left child, ensuring that the rightmost node is encountered first.
  • Maintain a list (right_view[]) where right_view[level] stores the rightmost node at that level. The right_view list contains nodes arranged from top to bottom, forming the right-side view of the tree.

Company Tags

AMD Micron Technology Unity Technologies Databricks NVIDIA Seagate Technology Bloomberg Deloitte Alibaba Goldman Sachs Square Bain & Company IBM Docker Ernst & Young Morgan Stanley Snowflake Pinterest Johnson & Johnson Stripe Western Digital Roche OYO Rooms DoorDash Lyft Google Microsoft Amazon Meta Apple Netflix Adobe