Bottom View of a Binary Tree
Last Updated :
01 Nov, 2024
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(" "));
Similar Reads
Left View of a Binary Tree
Given a Binary Tree, the task is to print the left view of the Binary Tree. The left view of a Binary Tree is a set of leftmost nodes for every level. Examples: Example 1 : The Green colored nodes represents the left view in the below Binary tree. Example 2: The Green colored nodes represents the le
15+ min read
Print Bottom-Right View of a Binary Tree
Given a Binary Tree, print Bottom-Right view of it. The Bottom Right view of a Binary Tree is a set of nodes visible when the tree is visited from Bottom Right side, return the values of the nodes ordered from right to left. In the bottom-right view, on viewing the tree at an angle of 45 degrees fro
11 min read
Sum of nodes in bottom view of Binary Tree
Given a binary tree, the task is to return the sum of nodes in the bottom view of the given Binary Tree. The bottom view of a binary tree is the set of nodes visible when the tree is viewed from the bottom. Note: If there are multiple bottom-most nodes for a horizontal distance from the root, then t
15+ min read
Left View of a Binary Tree Using Stack
Given a Binary Tree, the task is to print the left view of the Binary Tree. The left view of a Binary Tree is a set of leftmost nodes for every level. Examples: Example 1 : The Green colored nodes represents the left view in the below Binary tree. Example 2: The Green colored nodes represents the le
8 min read
Types of Binary Tree
We have discussed Introduction to Binary Tree in set 1 and the Properties of Binary Tree in Set 2. In this post, common types of Binary Trees are discussed. Types of Binary Tree based on the number of children:Following are the types of Binary Tree based on the number of children: Full Binary TreeDe
7 min read
Sum of nodes in top view of binary tree
Top view of a binary tree is the set of nodes visible when the tree is viewed from the top. Given a binary tree, the task is to print the sum of nodes in top view.Examples: Input: 1 / \ 2 3 / \ \ 4 5 6 Output: 16 Input: 1 / \ 2 3 \ 4 \ 5 \ 6 Output: 12 Approach: The idea is to put nodes of same hori
13 min read
Print Nodes in Top View of Binary Tree
Given a binary tree. The task is to find the top view of the binary tree. The top view of a binary tree is the set of nodes visible when the tree is viewed from the top. Note: Return the nodes from the leftmost node to the rightmost node.If two nodes are at the same position (horizontal distance) an
15+ min read
Print Nodes in Top View of Binary Tree
Given a binary tree. The task is to find the top view of the binary tree. The top view of a binary tree is the set of nodes visible when the tree is viewed from the top. Note: Return the nodes from the leftmost node to the rightmost node.If two nodes are at the same position (horizontal distance) an
15+ min read
Deletion in a Binary Tree
Given a binary tree, the task is to delete a given node from it by making sure that the tree shrinks from the bottom (i.e. the deleted node is replaced by the bottom-most and rightmost node). This is different from BST deletion. Here we do not have any order among elements, so we replace them with t
12 min read
Validate the Binary Tree Nodes
Given N nodes numbered from 0 to n-1, also given the E number of directed edges, determine whether the given nodes all together form a single binary tree or not. Examples: Input: N = 4, edges[][] = [[0 1], [0 2], [2 3]] Output: trueExplanation: Form a single binary tree with a unique root node. Inpu
7 min read
Level of a Node in Binary Tree
Given a Binary Tree and a key, the task is to find the level of key in the Binary Tree. Examples: Input : key = 4 Output: 3Explanation: The level of the key in above binary tree is 3.Input : key = 10 Output: -1Explanation: Key is not present in the above Binary tree. Table of Content [Expected Appro
12 min read
Print nodes in the Top View of Binary Tree | Set 3
Top view of a binary tree is the set of nodes visible when the tree is viewed from the top. Given a binary tree, print the top view of it. The output nodes can be printed in any order. Expected time complexity is O(n) A node x is there in output if x is the topmost node at its horizontal distance. H
9 min read
Largest BST in a Binary Tree
Given a Binary Tree, the task is to return the size of the largest subtree which is also a Binary Search Tree (BST). If the complete Binary Tree is BST, then return the size of the whole tree. Examples: Input: Output: 3 Explanation: The below subtree is the maximum size BST: Input: Output: 3 Explana
14 min read
Vertical width of Binary tree | Set 2
Given a binary tree, find the vertical width of the binary tree. The width of a binary tree is the number of vertical paths. Examples: Input : 7 / \ 6 5 / \ / \ 4 3 2 1 Output : 5 Input : 1 / \ 2 3 / \ / \ 4 5 6 7 \ \ 8 9 Output : 6 Prerequisite: Print Binary Tree in Vertical order In this image, th
5 min read
What is Binary Tree?
A binary tree is a type of tree data structure in which each node can have at most two child nodes, known as the left child and the right child. Each node of the tree consists of - data and pointers to the left and the right child. Properties of a Binary Tree: The following are some of the important
3 min read
Find Minimum Depth of a Binary Tree
Given a binary tree, find its minimum depth. The minimum depth is the number of nodes along the shortest path from the root node down to the nearest leaf node. For example, minimum depth of below Binary Tree is 2. Note that the path must end on a leaf node. For example, the minimum depth of below Bi
15 min read
Vertical width of Binary tree | Set 1
Given a Binary tree, the task is to find the vertical width of the Binary tree. The width of a binary tree is the number of vertical paths in the Binary tree. Examples: Input: Output: 6Explanation: In this image, the tree contains 6 vertical lines which are the required width of the tree. Input : 7
14 min read
Full Binary Tree
What is a Binary Tree? A binary tree is a tree data structure with a maximum of 2 children per node. We commonly refer to them as the left and right child as each element in a binary tree may only have two children. What is a Full Binary Tree? A full binary tree is a binary tree with either zero or
2 min read
Boundary Traversal of binary tree
Given a binary tree, the task is to find the boundary nodes of the binary tree Anti-Clockwise starting from the root. The boundary includes: left boundary (nodes on left excluding leaf nodes)leaves (consist of only the leaf nodes)right boundary (nodes on right excluding leaf nodes)The left boundary
15+ min read