Bottom View of a Binary Tree
Last Updated :
23 Jul, 2025
Given a binary tree, 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.
Examples:
Example1: The Green nodes represent the bottom view of below binary tree.

Example2: The Green nodes represent the bottom view of below binary tree.

[Expected Approach - 1] Using level order traversal - O(nlogn) Time and O(n) Space
The idea is to perform a level order traversal (BFS) while tracking each node's horizontal distance (HD) from the root. Starting with the root at HD 0, left children have HD - 1 and right children have HD + 1. We use a queue to process nodes level by level, updating a hashmap with each node's data at its corresponding HD, ensuring that the last node processed at each HD represents the bottom view. By tracking the minimum and maximum HDs during traversal, we know the full range of HDs. After traversal, we extract nodes from the map in order of their HDs, which gives us the bottom view of the tree as seen from directly below.
Below is the implementation of the above approach:
C++
// C++ code to find the bottom view
// using level-order traversal
#include <bits/stdc++.h>
using namespace std;
class Node {
public:
int data;
Node *left, *right;
Node(int x) {
data = x;
left = right = nullptr;
}
};
// Function to return the bottom view
// of the binary tree
vector<int> bottomView(Node *root) {
if (!root) return {};
// Map to store the last node at each
// horizontal distance (HD)
map<int, int> hdMap;
// Queue to store nodes and their HD
queue<pair<Node*, int>> q;
// Start level order traversal with
// root at HD 0
q.push({root, 0});
while (!q.empty()) {
// Get current node and its HD
Node *curr = q.front().first;
int hd = q.front().second;
q.pop();
// Update the map with the current
// node's data
hdMap[hd] = curr->data;
// Traverse the left subtree, HD - 1
if (curr->left) {
q.push({curr->left, hd - 1});
}
// Traverse the right subtree, HD + 1
if (curr->right) {
q.push({curr->right, hd + 1});
}
}
// Extract bottom view nodes
// from the map
vector<int> result;
// Iterate through the map in
// sorted HD order
for (auto it : hdMap) {
result.push_back(it.second);
}
return result;
}
void printArray(vector<int>& arr) {
cout << endl;
}
int main() {
// Representation of the input tree:
// 20
// / \
// 8 22
// / \ \
// 5 3 25
// / \
// 10 14
Node *root = new Node(20);
root->left = new Node(8);
root->right = new Node(22);
root->left->left = new Node(5);
root->left->right = new Node(3);
root->left->right->left = new Node(10);
root->left->right->right = new Node(14);
root->right->right = new Node(25);
vector<int> result = bottomView(root);
for (int val : result) {
cout << val << " ";
}
return 0;
}
Java
// Java code to find the bottom view
// using level-order traversal
import java.util.*;
class Node {
int data;
Node left, right;
Node(int x) {
data = x;
left = right = null;
}
}
class Pair {
Node node;
int hd;
Pair(Node node, int hd) {
this.node = node;
this.hd = hd;
}
}
class GfG {
// Function to return the bottom view
// of the binary tree
static ArrayList<Integer> bottomView(Node root) {
if (root == null) return new ArrayList<>();
// Map to store the last node at each
// horizontal distance (HD)
Map<Integer, Integer> hdMap = new TreeMap<>();
// Queue to store nodes and their
// horizontal distance
Queue<Pair> q = new LinkedList<>();
// Start level order traversal with
// root at HD 0
q.add(new Pair(root, 0));
while (!q.isEmpty()) {
// Get current node and its HD
Node curr = q.peek().node;
int hd = q.peek().hd;
q.poll();
// Update the map with the current
// node's data
hdMap.put(hd, curr.data);
// Traverse the left subtree, HD - 1
if (curr.left != null) {
q.add(new Pair(curr.left, hd - 1));
}
// Traverse the right subtree, HD + 1
if (curr.right != null) {
q.add(new Pair(curr.right, hd + 1));
}
}
// Extract bottom view nodes
// from the map
ArrayList<Integer> result = new ArrayList<>();
// Iterate through the map in
// sorted HD order
for (int value : hdMap.values()) {
result.add(value);
}
return result;
}
public static void main(String[] args) {
// Representation of the input tree:
// 20
// / \
// 8 22
// / \ \
// 5 3 25
// / \
// 10 14
Node root = new Node(20);
root.left = new Node(8);
root.right = new Node(22);
root.left.left = new Node(5);
root.left.right = new Node(3);
root.left.right.left = new Node(10);
root.left.right.right = new Node(14);
root.right.right = new Node(25);
ArrayList<Integer> result = bottomView(root);
for (int val : result) {
System.out.print(val + " ");
}
}
}
Python
# Python code to find the bottom view
# using level-order traversal
from collections import deque, defaultdict
class Node:
def __init__(self, data):
self.data = data
self.left = None
self.right = None
# Function to return the bottom view of the
# binary tree
def bottomView(root):
if not root:
return []
# Dictionary to store the last node at
# each horizontal distance (HD)
hdMap = {}
# Queue to store nodes and their horizontal
# distance
q = deque([(root, 0)])
while q:
# Get current node and its HD
curr, hd = q.popleft()
# Update the map with the current
# node's data
hdMap[hd] = curr.data
# Traverse the left subtree, HD - 1
if curr.left:
q.append((curr.left, hd - 1))
# Traverse the right subtree, HD + 1
if curr.right:
q.append((curr.right, hd + 1))
# Extract bottom view nodes from the map,
# sorted by HD
result = [hdMap[hd] for hd in sorted(hdMap)]
return result
if __name__ == "__main__":
# Representation of the input tree:
# 20
# / \
# 8 22
# / \ \
# 5 3 25
# / \
# 10 14
root = Node(20)
root.left = Node(8)
root.right = Node(22)
root.left.left = Node(5)
root.left.right = Node(3)
root.left.right.left = Node(10)
root.left.right.right = Node(14)
root.right.right = Node(25)
result = bottomView(root)
print(" ".join(map(str, result)))
C#
// C# code to find the bottom view
// using level-order traversal
using System;
using System.Collections.Generic;
class Node {
public int data;
public Node left, right;
public Node(int x) {
data = x;
left = right = null;
}
}
class GfG {
// Function to return the bottom
// view of the tree
static List<int> bottomView(Node root) {
if (root == null) return new List<int>();
// Dictionary to store last node at
// each horizontal dist
SortedDictionary<int, int> hdMap =
new SortedDictionary<int, int>();
// Queue to store nodes and their
// horizontal distance
Queue<Tuple<Node, int>> q =
new Queue<Tuple<Node, int>>();
// Start level order traversal with
// root at HD 0
q.Enqueue(new Tuple<Node, int>(root, 0));
while (q.Count > 0) {
// Get current node and its
// horizontal distance
var currPair = q.Dequeue();
Node curr = currPair.Item1;
int hd = currPair.Item2;
// Update the map with the
// current node's data
hdMap[hd] = curr.data;
// Traverse the left subtree, HD - 1
if (curr.left != null) {
q.Enqueue(new Tuple<Node,
int>(curr.left, hd - 1));
}
// Traverse the right subtree, HD + 1
if (curr.right != null) {
q.Enqueue(new Tuple<Node,
int>(curr.right, hd + 1));
}
}
// Extract bottom view nodes
// from the map
List<int> result = new List<int>();
foreach (var entry in hdMap) {
result.Add(entry.Value);
}
return result;
}
static void Main() {
// Representation of the input tree:
// 20
// / \
// 8 22
// / \ \
// 5 3 25
// / \
// 10 14
Node root = new Node(20);
root.left = new Node(8);
root.right = new Node(22);
root.left.left = new Node(5);
root.left.right = new Node(3);
root.left.right.left = new Node(10);
root.left.right.right = new Node(14);
root.right.right = new Node(25);
List<int> result = bottomView(root);
foreach (int val in result) {
Console.Write(val + " ");
}
}
}
JavaScript
// JavaScript code to find the bottom view
// using level-order traversal
class Node {
constructor(data) {
this.data = data;
this.left = null;
this.right = null;
}
}
function bottomView(root) {
if (!root) return [];
// Map to store last node at each
// horizontal distance
const hdMap = new Map();
// Queue to store nodes and their
// horizontal distance
const queue = [{ node: root, hd: 0 }];
while (queue.length > 0) {
const { node, hd } = queue.shift();
// Update the map with the current
// node's data
hdMap.set(hd, node.data);
// Traverse the left subtree, HD - 1
if (node.left) {
queue.push({ node: node.left, hd: hd - 1 });
}
// Traverse the right subtree, HD + 1
if (node.right) {
queue.push({ node: node.right, hd: hd + 1 });
}
}
// Extract bottom view nodes from the map
const result = [];
[...hdMap.keys()].sort((a, b) => a - b).forEach(hd => {
result.push(hdMap.get(hd));
});
return result;
}
// Representation of the input tree:
// 20
// / \
// 8 22
// / \ \
// 5 3 25
// / \
// 10 14
const root = new Node(20);
root.left = new Node(8);
root.right = new Node(22);
root.left.left = new Node(5);
root.left.right = new Node(3);
root.left.right.left = new Node(10);
root.left.right.right = new Node(14);
root.right.right = new Node(25);
const result = bottomView(root);
console.log(result.join(" "));
[Expected Approach - 2] Using Depth first search - O(nlogn) Time and O(n) Space
Create a hashmap where the key is the horizontal distance and the value is a pair(a, b) where a is the value of the node and b is the height of the node. Perform a pre-order traversal of the tree. If the current node at a horizontal distance of h is the first seen, insert it into the map. Otherwise, compare the node with the existing one in map and if the height of the new node is greater, update the Map.
Below is the implementation of the above approach:
C++
// C++ code to find the bottom view
// using depth-first search (DFS)
#include <bits/stdc++.h>
using namespace std;
struct Node {
int data;
Node *left, *right;
Node(int x) {
data = x;
left = right = nullptr;
}
};
// Helper function to perform DFS and
// update the bottom view
void dfs(Node* root, int hd, int depth,
map<int, pair<int, int>>& hdMap) {
if (!root) return;
// If this horizontal distance is
// being visited for the first time or
// we're at a deeper level, update it
if (hdMap.find(hd) == hdMap.end()
|| depth >= hdMap[hd].second) {
hdMap[hd] = {root->data, depth};
}
// Traverse the left subtree with
// HD - 1 and increased depth
dfs(root->left, hd - 1, depth + 1, hdMap);
// Traverse the right subtree with
// HD + 1 and increased depth
dfs(root->right, hd + 1, depth + 1, hdMap);
}
// Function to return the bottom view
// of the binary tree using DFS
vector<int> bottomView(Node *root) {
if (!root) return {};
// Map to store the last node's data and its depth
// at each horizontal distance (HD)
map<int, pair<int, int>> hdMap;
// Start DFS with root at HD 0 and depth 0
dfs(root, 0, 0, hdMap);
// Extract bottom view nodes from the map
vector<int> result;
// Iterate through the map in
// sorted HD order
for (auto it : hdMap) {
result.push_back(it.second.first);
}
return result;
}
int main() {
// Representation of the input tree:
// 20
// / \
// 8 22
// / \ \
// 5 3 25
// / \
// 10 14
Node *root = new Node(20);
root->left = new Node(8);
root->right = new Node(22);
root->left->left = new Node(5);
root->left->right = new Node(3);
root->left->right->left = new Node(10);
root->left->right->right = new Node(14);
root->right->right = new Node(25);
vector<int> result = bottomView(root);
for (int val : result) {
cout << val << " ";
}
return 0;
}
Java
// Java code to find the bottom view
// using depth-first search (DFS)
import java.util.*;
class Node {
int data;
Node left, right;
Node(int x) {
data = x;
left = right = null;
}
}
class GfG {
// Helper function to perform DFS and update
// the bottom view
static void dfs(Node root, int hd, int depth,
Map<Integer, Pair> hdMap) {
if (root == null) return;
// If this horizontal distance is
// being visited for the first time or
// we're at a deeper level, update it
if (!hdMap.containsKey(hd)
|| depth >= hdMap.get(hd).depth) {
hdMap.put(hd, new Pair(root.data, depth));
}
// Traverse the left subtree with
// HD - 1 and increased depth
dfs(root.left, hd - 1, depth + 1, hdMap);
// Traverse the right subtree
// with HD + 1 and increased depth
dfs(root.right, hd + 1, depth + 1, hdMap);
}
// Function to return the bottom view of
// the binary tree using DFS
static ArrayList<Integer> bottomView(Node root) {
if (root == null) return new ArrayList<>();
// Map to store the last node's data and its depth
// at each horizontal distance (HD)
Map<Integer, Pair> hdMap = new TreeMap<>();
// Start DFS with root at HD 0 and depth 0
dfs(root, 0, 0, hdMap);
// Extract bottom view nodes from the map
ArrayList<Integer> result = new ArrayList<>();
// Iterate through the map in sorted HD order
for (Pair value : hdMap.values()) {
result.add(value.data);
}
return result;
}
// Pair class to store node data and depth
static class Pair {
int data, depth;
Pair(int data, int depth) {
this.data = data;
this.depth = depth;
}
}
public static void main(String[] args) {
// Representation of the input tree:
// 20
// / \
// 8 22
// / \ \
// 5 3 25
// / \
// 10 14
Node root = new Node(20);
root.left = new Node(8);
root.right = new Node(22);
root.left.left = new Node(5);
root.left.right = new Node(3);
root.left.right.left = new Node(10);
root.left.right.right = new Node(14);
root.right.right = new Node(25);
ArrayList<Integer> result = bottomView(root);
for (int val : result) {
System.out.print(val + " ");
}
}
}
Python
# Python code to find the bottom view
# using depth-first search (DFS)
class Node:
def __init__(self, data):
self.data = data
self.left = None
self.right = None
# Helper function to perform DFS and update
# the bottom view
def dfs(root, hd, depth, hd_map):
if not root:
return
# If this horizontal distance is being
# visited for the first time
# or we're at a deeper level, update it
if hd not in hd_map or depth >= hd_map[hd][1]:
hd_map[hd] = (root.data, depth)
# Traverse the left subtree with HD - 1
# and increased depth
dfs(root.left, hd - 1, depth + 1, hd_map)
# Traverse the right subtree with HD + 1
# and increased depth
dfs(root.right, hd + 1, depth + 1, hd_map)
# Function to return the bottom view of the
# binary tree using DFS
def bottomView(root):
if not root:
return []
# Dictionary to store the last node's data
# and its depth at each horizontal distance (HD)
hd_map = {}
# Start DFS with root at HD 0 and depth 0
dfs(root, 0, 0, hd_map)
# Extract bottom view nodes from the dictionary
result = []
# Iterate through the dictionary in
# sorted HD order
for hd in sorted(hd_map.keys()):
result.append(hd_map[hd][0])
return result
if __name__ == "__main__":
# Representation of the input tree:
# 20
# / \
# 8 22
# / \ \
# 5 3 25
# / \
# 10 14
root = Node(20)
root.left = Node(8)
root.right = Node(22)
root.left.left = Node(5)
root.left.right = Node(3)
root.left.right.left = Node(10)
root.left.right.right = Node(14)
root.right.right = Node(25)
result = bottomView(root)
print(" ".join(map(str, result)))
C#
// C# code to find the bottom view
// using depth-first search (DFS)
using System;
using System.Collections.Generic;
class Node {
public int data;
public Node left, right;
public Node(int x) {
data = x;
left = right = null;
}
}
class GfG {
// Helper function to perform DFS and update
// the bottom view
static void DFS(Node root, int hd, int depth,
Dictionary<int, (int, int)> hdMap) {
if (root == null) return;
// If this horizontal distance is being visited
// for the first time or we're at a deeper
// level, update it
if (!hdMap.ContainsKey(hd)
|| depth >= hdMap[hd].Item2) {
hdMap[hd] = (root.data, depth);
}
// Traverse the left subtree with HD - 1
// and increased depth
DFS(root.left, hd - 1, depth + 1, hdMap);
// Traverse the right subtree with HD + 1
// and increased depth
DFS(root.right, hd + 1, depth + 1, hdMap);
}
// Function to return the bottom view of
// the binary tree using DFS
static List<int> bottomView(Node root) {
if (root == null) return new List<int>();
// Dictionary to store the last node's data
// and its depth at each horizontal distance (HD)
var hdMap = new Dictionary<int, (int, int)>();
// Start DFS with root at HD 0 and depth 0
DFS(root, 0, 0, hdMap);
// Extract bottom view nodes from the dictionary
var result = new List<int>();
// Iterate through the dictionary in
// sorted HD order
foreach (var key in new
SortedSet<int>(hdMap.Keys)) {
result.Add(hdMap[key].Item1);
}
return result;
}
static void Main() {
// Representation of the input tree:
// 20
// / \
// 8 22
// / \ \
// 5 3 25
// / \
// 10 14
Node root = new Node(20);
root.left = new Node(8);
root.right = new Node(22);
root.left.left = new Node(5);
root.left.right = new Node(3);
root.left.right.left = new Node(10);
root.left.right.right = new Node(14);
root.right.right = new Node(25);
List<int> result = bottomView(root);
foreach (int val in result) {
Console.Write(val + " ");
}
}
}
JavaScript
// Javascript code to find the bottom view
// using depth-first search (DFS)
class Node {
constructor(data) {
this.data = data;
this.left = null;
this.right = null;
}
}
// Helper function to perform DFS and
// update the bottom view
function dfs(root, hd, depth, hdMap) {
if (!root) return;
// If this horizontal distance is being
// visited for the first time
// or we're at a deeper level, update it
if (!(hd in hdMap) || depth >= hdMap[hd][1]) {
hdMap[hd] = [root.data, depth];
}
// Traverse the left subtree with HD - 1
// and increased depth
dfs(root.left, hd - 1, depth + 1, hdMap);
// Traverse the right subtree with
// HD + 1 and increased depth
dfs(root.right, hd + 1, depth + 1, hdMap);
}
// Function to return the bottom view of
// the binary tree using DFS
function bottomView(root) {
if (!root) return [];
// Map to store the last node's data and its
// depth at each horizontal distance (HD)
const hdMap = {};
// Start DFS with root at HD 0 and depth 0
dfs(root, 0, 0, hdMap);
// Extract bottom view nodes from the map
const result = [];
// Get the keys (horizontal distances) in sorted order
const sortedKeys
= Object.keys(hdMap).map(Number).sort((a, b) => a - b);
// Iterate through the map in sorted HD order
for (const key of sortedKeys) {
result.push(hdMap[key][0]);
}
return result;
}
// Representation of the input tree:
// 20
// / \
// 8 22
// / \ \
// 5 3 25
// / \
// 10 14
const root = new Node(20);
root.left = new Node(8);
root.right = new Node(22);
root.left.left = new Node(5);
root.left.right = new Node(3);
root.left.right.left = new Node(10);
root.left.right.right = new Node(14);
root.right.right = new Node(25);
const result = bottomView(root);
console.log(result.join(" "));
[Alternate Approach] Using Hashing - O(n) Time and O(n) Space
Note : This solution might not give output nodes in any specific order.
The idea is to create a hashmap where the key is the horizontal distance and the value is a int x, where x is the value of the node. Perform a level order traversal of the tree. For every node at a horizontal distance of h we will store its value in map.
Below is the implementation of the above approach:
C++
// C++ code to find the bottom view using
// hashmap
#include <bits/stdc++.h>
using namespace std;
struct Node {
int data;
Node *left, *right;
Node(int x) {
data = x;
left = right = nullptr;
}
};
// Function to return the bottom view of
// the binary tree
vector<int> bottomView(Node *root) {
// if root is NULL, return empty vector
if (!root) return {};
// Unordered map to store <vertical_index,
// root->data>
unordered_map<int, int> hash;
// Store the leftmost index to help in
// left-to-right traversal
int leftmost = 0;
// Queue for level order traversal with
// pair<Node*, vertical index>
queue<pair<Node*, int>> q;
// Push the root with vertical index 0
q.push({root, 0});
while (!q.empty()) {
// Store q.front() in top variable
auto top = q.front();
q.pop();
// Current node
Node *curr = top.first;
// Vertical index of the current node
int ind = top.second;
// Update the vertical index -> node data
hash[ind] = curr->data;
// Track the leftmost vertical index
leftmost = min(ind, leftmost);
// Traverse left child with vertical
// index ind - 1
if (curr->left) {
q.push({curr->left, ind - 1});
}
// Traverse right child with vertical
// index ind + 1
if (curr->right) {
q.push({curr->right, ind + 1});
}
}
// Vector to store the final bottom view
vector<int> ans;
// Traverse each value in hash from
// leftmost to rightmost
while (hash.find(leftmost) != hash.end()) {
ans.push_back(hash[leftmost++]);
}
return ans;
}
int main() {
// Representation of the input tree:
// 20
// / \
// 8 22
// / \ \
// 5 3 25
// / \
// 10 14
Node *root = new Node(20);
root->left = new Node(8);
root->right = new Node(22);
root->left->left = new Node(5);
root->left->right = new Node(3);
root->left->right->left = new Node(10);
root->left->right->right = new Node(14);
root->right->right = new Node(25);
vector<int> result = bottomView(root);
for (int val : result) {
cout << val << " ";
}
return 0;
}
Java
// Java code to find the bottom view using
// hashmap
import java.util.*;
class Node {
int data;
Node left, right;
Node(int x) {
data = x;
left = right = null;
}
}
class GfG {
// Function to return the bottom view of
// the binary tree
static ArrayList<Integer> bottomView(Node root) {
// if root is null, return empty list
if (root == null) return new ArrayList<>();
// HashMap to store <vertical_index,
// root.data>
HashMap<Integer, Integer> hash = new HashMap<>();
// Store the leftmost index to help in
// left-to-right traversal
int leftmost = 0;
// Queue for level order traversal with
// pair<Node, vertical index>
Queue<Map.Entry<Node, Integer>> q =
new LinkedList<>();
// Push the root with vertical index 0
q.offer(new AbstractMap.SimpleEntry<>(root, 0));
while (!q.isEmpty()) {
// Store q.poll() in top variable
Map.Entry<Node, Integer> top = q.poll();
// Current node
Node curr = top.getKey();
// Vertical index of the current node
int ind = top.getValue();
// Update the vertical index -> node data
hash.put(ind, curr.data);
// Track the leftmost vertical index
leftmost = Math.min(ind, leftmost);
// Traverse left child with vertical index ind - 1
if (curr.left != null) {
q.offer(new AbstractMap.SimpleEntry<>
(curr.left, ind - 1));
}
// Traverse right child with vertical index ind + 1
if (curr.right != null) {
q.offer(new AbstractMap.SimpleEntry<>
(curr.right, ind + 1));
}
}
// List to store the final bottom view
ArrayList<Integer> ans = new ArrayList<>();
// Traverse each value in hash from
// leftmost to rightmost
while (hash.containsKey(leftmost)) {
ans.add(hash.get(leftmost++));
}
return ans;
}
public static void main(String[] args) {
// Representation of the input tree:
// 20
// / \
// 8 22
// / \ \
// 5 3 25
// / \
// 10 14
Node root = new Node(20);
root.left = new Node(8);
root.right = new Node(22);
root.left.left = new Node(5);
root.left.right = new Node(3);
root.left.right.left = new Node(10);
root.left.right.right = new Node(14);
root.right.right = new Node(25);
ArrayList<Integer> result = bottomView(root);
for (int val : result) {
System.out.print(val + " ");
}
}
}
Python
# Python code to find the bottom view using
# hashmap
from collections import deque, defaultdict
class Node:
def __init__(self, x):
self.data = x
self.left = None
self.right = None
# Function to return the bottom view of
# the binary tree
def bottom_view(root):
# if root is None, return empty list
if not root:
return []
# Dictionary to store <vertical_index,
# root.data>
hash_map = {}
# Store the leftmost index to help in
# left-to-right traversal
leftmost = 0
# Queue for level order traversal with
# (Node, vertical index) pairs
q = deque([(root, 0)])
while q:
# Store q.popleft() in top variable
top = q.popleft()
# Current node
curr = top[0]
# Vertical index of the current node
ind = top[1]
# Update the vertical index -> node data
hash_map[ind] = curr.data
# Track the leftmost vertical index
leftmost = min(ind, leftmost)
# Traverse left child with vertical index
# ind - 1
if curr.left:
q.append((curr.left, ind - 1))
# Traverse right child with vertical index
# ind + 1
if curr.right:
q.append((curr.right, ind + 1))
# List to store the final bottom view
ans = []
# Traverse each value in hash_map from
# leftmost to rightmost
while leftmost in hash_map:
ans.append(hash_map[leftmost])
leftmost += 1
return ans
if __name__ == "__main__":
# Representation of the input tree:
# 20
# / \
# 8 22
# / \ \
# 5 3 25
# / \
# 10 14
root = Node(20)
root.left = Node(8)
root.right = Node(22)
root.left.left = Node(5)
root.left.right = Node(3)
root.left.right.left = Node(10)
root.left.right.right = Node(14)
root.right.right = Node(25)
result = bottom_view(root)
for val in result:
print(val, end=" ")
C#
// C# code to find the bottom view using
// dictionary
using System;
using System.Collections.Generic;
class Node {
public int data;
public Node left, right;
public Node(int x) {
data = x;
left = right = null;
}
}
class GfG {
// Function to return the bottom view of
// the binary tree
static List<int> BottomView(Node root) {
// if root is null, return empty list
if (root == null) return new List<int>();
// Dictionary to store <vertical_index,
// root.data>
Dictionary<int, int> hash = new Dictionary
<int, int>();
// Store the leftmost index to help in
// left-to-right traversal
int leftmost = 0;
// Queue for level order traversal with
// (Node, vertical index) pairs
Queue<KeyValuePair<Node, int>> q
= new Queue<KeyValuePair<Node, int>>();
// Enqueue the root with vertical index 0
q.Enqueue(new KeyValuePair<Node, int>(root, 0));
while (q.Count > 0) {
// Store q.Dequeue() in top
// variable
var top = q.Dequeue();
// Current node
Node curr = top.Key;
// Vertical index of the current node
int ind = top.Value;
// Update the vertical index -> node data
hash[ind] = curr.data;
// Track the leftmost vertical index
leftmost = Math.Min(ind, leftmost);
// Traverse left child with vertical
// index ind - 1
if (curr.left != null) {
q.Enqueue(new KeyValuePair<Node,
int>(curr.left, ind - 1));
}
// Traverse right child with vertical
// index ind + 1
if (curr.right != null) {
q.Enqueue(new KeyValuePair<Node,
int>(curr.right, ind + 1));
}
}
// List to store the final bottom view
List<int> ans = new List<int>();
// Traverse each value in hash from
// leftmost to rightmost
while (hash.ContainsKey(leftmost)) {
ans.Add(hash[leftmost++]);
}
return ans;
}
static void Main(string[] args) {
// Representation of the input tree:
// 20
// / \
// 8 22
// / \ \
// 5 3 25
// / \
// 10 14
Node root = new Node(20);
root.left = new Node(8);
root.right = new Node(22);
root.left.left = new Node(5);
root.left.right = new Node(3);
root.left.right.left = new Node(10);
root.left.right.right = new Node(14);
root.right.right = new Node(25);
List<int> result = BottomView(root);
foreach (int val in result) {
Console.Write(val + " ");
}
}
}
JavaScript
// JavaScript code to find the bottom view using
// hashmap
class Node {
constructor(x) {
this.data = x;
this.left = null;
this.right = null;
}
}
// Function to return the bottom view of
// the binary tree
function bottomView(root) {
// if root is null, return empty array
if (!root) return [];
// Map to store <vertical_index, root.data>
const hash = new Map();
// Store the leftmost index to help in
// left-to-right traversal
let leftmost = 0;
// Queue for level order traversal with
// [Node, vertical index] pairs
const q = [];
// Push the root with vertical index 0
q.push([root, 0]);
while (q.length > 0) {
// Store q.shift() in top variable
const top = q.shift();
// Current node
const curr = top[0];
// Vertical index of the current node
const ind = top[1];
// Update the vertical index -> node data
hash.set(ind, curr.data);
// Track the leftmost vertical index
leftmost = Math.min(ind, leftmost);
// Traverse left child with vertical
// index ind - 1
if (curr.left) {
q.push([curr.left, ind - 1]);
}
// Traverse right child with vertical
// index ind + 1
if (curr.right) {
q.push([curr.right, ind + 1]);
}
}
// Array to store the final bottom view
const ans = [];
// Traverse each value in hash from
// leftmost to rightmost
while (hash.has(leftmost)) {
ans.push(hash.get(leftmost++));
}
return ans;
}
// Representation of the input tree:
// 20
// / \
// 8 22
// / \ \
// 5 3 25
// / \
// 10 14
const root = new Node(20);
root.left = new Node(8);
root.right = new Node(22);
root.left.left = new Node(5);
root.left.right = new Node(3);
root.left.right.left = new Node(10);
root.left.right.right = new Node(14);
root.right.right = new Node(25);
const result = bottomView(root);
console.log(result.join(" "));
Print Bottom View of Binary Tree
Similar Reads
Basics & Prerequisites
Data Structures
Array Data StructureIn this article, we introduce array, implementation in different popular languages, its basic operations and commonly seen problems / interview questions. An array stores items (in case of C/C++ and Java Primitive Arrays) or their references (in case of Python, JS, Java Non-Primitive) at contiguous
3 min read
String in Data StructureA string is a sequence of characters. The following facts make string an interesting data structure.Small set of elements. Unlike normal array, strings typically have smaller set of items. For example, lowercase English alphabet has only 26 characters. ASCII has only 256 characters.Strings are immut
2 min read
Hashing in Data StructureHashing is a technique used in data structures that efficiently stores and retrieves data in a way that allows for quick access. Hashing involves mapping data to a specific index in a hash table (an array of items) using a hash function. It enables fast retrieval of information based on its key. The
2 min read
Linked List Data StructureA linked list is a fundamental data structure in computer science. It mainly allows efficient insertion and deletion operations compared to arrays. Like arrays, it is also used to implement other data structures like stack, queue and deque. Hereâs the comparison of Linked List vs Arrays Linked List:
2 min read
Stack Data StructureA Stack is a linear data structure that follows a particular order in which the operations are performed. The order may be LIFO(Last In First Out) or FILO(First In Last Out). LIFO implies that the element that is inserted last, comes out first and FILO implies that the element that is inserted first
2 min read
Queue Data StructureA Queue Data Structure is a fundamental concept in computer science used for storing and managing data in a specific order. It follows the principle of "First in, First out" (FIFO), where the first element added to the queue is the first one to be removed. It is used as a buffer in computer systems
2 min read
Tree Data StructureTree Data Structure is a non-linear data structure in which a collection of elements known as nodes are connected to each other via edges such that there exists exactly one path between any two nodes. Types of TreeBinary Tree : Every node has at most two childrenTernary Tree : Every node has at most
4 min read
Graph Data StructureGraph Data Structure is a collection of nodes connected by edges. It's used to represent relationships between different entities. If you are looking for topic-wise list of problems on different topics like DFS, BFS, Topological Sort, Shortest Path, etc., please refer to Graph Algorithms. Basics of
3 min read
Trie Data StructureThe Trie data structure is a tree-like structure used for storing a dynamic set of strings. It allows for efficient retrieval and storage of keys, making it highly effective in handling large datasets. Trie supports operations such as insertion, search, deletion of keys, and prefix searches. In this
15+ min read
Algorithms
Searching AlgorithmsSearching algorithms are essential tools in computer science used to locate specific items within a collection of data. In this tutorial, we are mainly going to focus upon searching in an array. When we search an item in an array, there are two most common algorithms used based on the type of input
2 min read
Sorting AlgorithmsA Sorting Algorithm is used to rearrange a given array or list of elements in an order. For example, a given array [10, 20, 5, 2] becomes [2, 5, 10, 20] after sorting in increasing order and becomes [20, 10, 5, 2] after sorting in decreasing order. There exist different sorting algorithms for differ
3 min read
Introduction to RecursionThe process in which a function calls itself directly or indirectly is called recursion and the corresponding function is called a recursive function. A recursive algorithm takes one step toward solution and then recursively call itself to further move. The algorithm stops once we reach the solution
14 min read
Greedy AlgorithmsGreedy algorithms are a class of algorithms that make locally optimal choices at each step with the hope of finding a global optimum solution. At every step of the algorithm, we make a choice that looks the best at the moment. To make the choice, we sometimes sort the array so that we can always get
3 min read
Graph AlgorithmsGraph is a non-linear data structure like tree data structure. The limitation of tree is, it can only represent hierarchical data. For situations where nodes or vertices are randomly connected with each other other, we use Graph. Example situations where we use graph data structure are, a social net
3 min read
Dynamic Programming or DPDynamic Programming is an algorithmic technique with the following properties.It is mainly an optimization over plain recursion. Wherever we see a recursive solution that has repeated calls for the same inputs, we can optimize it using Dynamic Programming. The idea is to simply store the results of
3 min read
Bitwise AlgorithmsBitwise algorithms in Data Structures and Algorithms (DSA) involve manipulating individual bits of binary representations of numbers to perform operations efficiently. These algorithms utilize bitwise operators like AND, OR, XOR, NOT, Left Shift, and Right Shift.BasicsIntroduction to Bitwise Algorit
4 min read
Advanced
Segment TreeSegment Tree is a data structure that allows efficient querying and updating of intervals or segments of an array. It is particularly useful for problems involving range queries, such as finding the sum, minimum, maximum, or any other operation over a specific range of elements in an array. The tree
3 min read
Pattern SearchingPattern searching algorithms are essential tools in computer science and data processing. These algorithms are designed to efficiently find a particular pattern within a larger set of data. Patten SearchingImportant Pattern Searching Algorithms:Naive String Matching : A Simple Algorithm that works i
2 min read
GeometryGeometry is a branch of mathematics that studies the properties, measurements, and relationships of points, lines, angles, surfaces, and solids. From basic lines and angles to complex structures, it helps us understand the world around us.Geometry for Students and BeginnersThis section covers key br
2 min read
Interview Preparation
Practice Problem