05(Aug) Bottom View of Binary Tree

05. Bottom View of Binary Tree

The problem can be found at the following link: Question Link

Problem Description

Given a binary tree, return an array where elements represent the bottom view of the binary tree from left to right.

Note: If there are multiple bottom-most nodes for a horizontal distance from the root, then the latter one in the level traversal is considered.

Example:

Input:

       1
     /   \
    3     2

Output:

3 1 2

Explanation: The bottom view of the binary tree will be 3, 1, 2.

My Approach

  1. Initialization:

    • Create a map bottomViewMap to store the bottom view nodes at each horizontal distance (hd).

    • Use a queue to perform a level order traversal of the tree, storing pairs of nodes and their corresponding horizontal distances.

  2. Level Order Traversal:

    • Push the root node with horizontal distance 0 into the queue.

    • For each node, update the bottomViewMap with the node's value at its horizontal distance.

    • If the node has a left child, push it into the queue with horizontal distance hd - 1.

    • If the node has a right child, push it into the queue with horizontal distance hd + 1.

  3. Extract Bottom View:

    • Iterate through the sorted keys of bottomViewMap to create the result array containing the bottom view of the binary tree.

Time and Auxiliary Space Complexity

  • Expected Time Complexity: O(n), as we perform a level order traversal of the tree visiting each node once.

  • Expected Auxiliary Space Complexity: O(n), as we use a map to store the nodes' values and a queue for the traversal.

Code

C++

Java

Python

Contribution and Support

For discussions, questions, or doubts related to this solution, feel free to connect on LinkedIn: Any Questions. Let’s make this learning journey more collaborative!

⭐ If you find this helpful, please give this repository a star! ⭐


📍Visitor Count

Last updated