Bottom View of a Binary Tree
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.
Table of Content
[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++ 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 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 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# 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 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(" "));
Output
5 10 3 14 25
[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++ 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 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 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# 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 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(" "));
Output
5 10 3 14 25
[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++ 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 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 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# 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 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(" "));
Output
5 10 3 14 25