VOOZH about

URL: https://www.geeksforgeeks.org/dsa/bottom-view-binary-tree/

⇱ Bottom View of a Binary Tree - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Bottom View of a Binary Tree

Last Updated : 6 Oct, 2025

Given the root of a binary tree, find the bottom view of the tree as a list of node values in order of increasing horizontal distance(HD).

  • The root has HD = 0.
  • The left child decreases HD by 1, and the right child increases HD by 1.
  • If multiple nodes share the same HD and depth, select the node that appears later in level-order traversal.

Return the values of these nodes from the leftmost to the rightmost horizontal distance.

Examples:

Input:

👁 bottom_view_of_binary_tree_4

Output: [4, 2, 5, 3, 6]
Explanation:

👁 bottom_view_of_binary_tree_3


Input:

👁 bottom_view_of_binary_tree_2

Output: [5, 10, 4, 28, 25]
Explanation: Here, 14 and 28 both have horizontal distance = 1 from root, but we are taking 28 in our answer as 28 appears later in the level order traversal.

👁 bottom_view_of_binary_tree_1

[Expected Approach - 1] Using DFS - O(n) Time and O(n) Space

The idea is to create a hashmap to store the horizontal distance and the bottom-most node having that horizontal distance wrt root node.
During DFS, if we encounter a node whose horizontal distance is not present in the map, add it to the map. If we encounter a node whose horizontal distance already exists as a key in the map:

  • Choose the node with greater depth.
  • If both nodes have the same depth, choose the current node, because it appears later in level order traversal.

Output
5 10 4 28 25 

[Expected Approach - 2] Using BFS - O(n) Time and O(n) Space

The idea is to do BFS while maintaining a map for horizontal distance (key) and the last node (value). The value for a certain distance is updated as we progress in the level order traversal.


Output
5 10 4 28 25 


Comment