Print Nodes in Top View of Binary Tree
Last Updated :
23 Jul, 2025
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) and are outside the shadow of the tree, consider the leftmost node only.
Examples:
Example 1: The Green colored nodes represents the top view in the below Binary tree.
Example 2: The Green colored nodes represents the top view in the below Binary tree.
Top view for example 2
Using DFS - O(n * log n) Time and O(n) Space
The idea is to use a Depth-First Search (DFS) approach to find the top view of a binary tree. We keep track of horizontal distance from root node. Start from the root node with a distance of 0. When we move to left child we subtract 1 and add 1 when we move to right child to distance of the current node. We use a HashMap to store the top most node that appears at a given horizontal distance. As we traverse the tree, we check if there is any node at current distance in hashmap . If it's the first node encountered at its horizontal distance ,we include it in the top view.
C++
// C++ program to print top
// view of binary tree
// using dfs
#include <bits/stdc++.h>
using namespace std;
class Node {
public:
int data;
Node* left;
Node* right;
Node(int val) {
data = val;
left = right = nullptr;
}
};
// DFS Helper to store top view nodes
void dfs(Node* node, int hd, int level,
map<int, pair<int, int>>& topNodes) {
if (!node) return;
// If horizontal distance is encountered for
// the first time or if it's at a higher level
if (topNodes.find(hd) == topNodes.end() ||
topNodes[hd].second > level) {
topNodes[hd] = {node->data, level};
}
// Recur for left and right subtrees
dfs(node->left, hd - 1, level + 1, topNodes);
dfs(node->right, hd + 1, level + 1, topNodes);
}
// DFS Approach to find the top view of a binary tree
vector<int> topView(Node* root) {
vector<int> result;
if (!root) return result;
// Horizontal distance -> {node's value, level}
map<int, pair<int, int>> topNodes;
// Start DFS traversal
dfs(root, 0, 0, topNodes);
// Collect nodes from the map
for (auto it : topNodes) {
result.push_back(it.second.first);
}
return result;
}
int main() {
// Create a sample binary tree
// 1
// / \
// 2 3
// / \ / \
// 4 5 6 7
Node* root = new Node(1);
root->left = new Node(2);
root->right = new Node(3);
root->left->left = new Node(4);
root->left->right = new Node(5);
root->right->left = new Node(6);
root->right->right = new Node(7);
vector<int> result = topView(root);
for (int i : result) {
cout << i << " ";
}
return 0;
}
Java
// Java program to print
// top view of binary tree
// using dfs
import java.util.*;
class Node {
int data;
Node left, right;
public Node(int val) {
data = val;
left = right = null;
}
}
class Pair<u, v> {
public u first;
public v second;
public Pair(u first, v second) {
this.first = first;
this.second = second;
}
public u getKey() {
return first;
}
public v getValue() {
return second;
}
}
class GfG {
// DFS Helper to store top view nodes
static void dfs(Node node, int hd, int level,
Map<Integer, Pair<Integer, Integer>> topNodes) {
if (node == null) return;
// If horizontal distance is encountered for
// the first time or if it's at a higher level
if (!topNodes.containsKey(hd) ||
topNodes.get(hd).getValue() > level) {
topNodes.put(hd, new Pair<>(node.data, level));
}
// Recur for left and right subtrees
dfs(node.left, hd - 1, level + 1, topNodes);
dfs(node.right, hd + 1, level + 1, topNodes);
}
// DFS Approach to find the top view of a binary tree
static ArrayList<Integer> topView(Node root) {
ArrayList<Integer> result = new ArrayList<>();
if (root == null) return result;
// Horizontal distance -> {node's value, level}
Map<Integer, Pair<Integer, Integer>> topNodes = new TreeMap<>();
// Start DFS traversal
dfs(root, 0, 0, topNodes);
// Collect nodes from the map
for (Pair<Integer, Integer> value : topNodes.values()) {
result.add(value.getKey());
}
return result;
}
public static void main(String[] args) {
// Create a sample binary tree
// 1
// / \
// 2 3
// / \ / \
// 4 5 6 7
Node root = new Node(1);
root.left = new Node(2);
root.right = new Node(3);
root.left.left = new Node(4);
root.left.right = new Node(5);
root.right.left = new Node(6);
root.right.right = new Node(7);
ArrayList<Integer> result = topView(root);
for (int i : result) {
System.out.print(i + " ");
}
}
}
Python
# Python program to print
# top view of binary tree
# using dfs
class Node:
def __init__(self, val):
self.data = val
self.left = None
self.right = None
def dfs(node, hd, level, top_nodes):
if not node:
return
# If horizontal distance is encountered for
# the first time or if it's at a higher level
if hd not in top_nodes or top_nodes[hd][1] > level:
top_nodes[hd] = (node.data, level)
# Recur for left and right subtrees
dfs(node.left, hd - 1, level + 1, top_nodes)
dfs(node.right, hd + 1, level + 1, top_nodes)
# DFS Approach to find the top view of a binary tree
def topView(root):
result = []
if not root:
return result
# Horizontal distance -> (node's value, level)
top_nodes = {}
# Start DFS traversal
dfs(root, 0, 0, top_nodes)
# Collect nodes from the map
for key in sorted(top_nodes):
result.append(top_nodes[key][0])
return result
if __name__ == "__main__":
# Create a sample binary tree
# 1
# / \
# 2 3
# / \ / \
# 4 5 6 7
root = Node(1)
root.left = Node(2)
root.right = Node(3)
root.left.left = Node(4)
root.left.right = Node(5)
root.right.left = Node(6)
root.right.right = Node(7)
result = topView(root)
print(" ".join(map(str, result)))
C#
// C# program to print
// top view of binary tree
// using dfs
using System;
using System.Collections.Generic;
class Node {
public int data;
public Node left, right;
public Node(int val) {
data = val;
left = right = null;
}
}
class GfG {
// DFS Helper to store top view nodes
static void Dfs(Node node, int hd, int level,
SortedDictionary<int, Tuple<int, int>> topNodes) {
if (node == null) return;
// If horizontal distance is encountered for
// the first time or if it's at a higher level
if (!topNodes.ContainsKey(hd) || topNodes[hd].Item2 > level) {
topNodes[hd] = new Tuple<int, int>(node.data, level);
}
// Recur for left and right subtrees
Dfs(node.left, hd - 1, level + 1, topNodes);
Dfs(node.right, hd + 1, level + 1, topNodes);
}
// DFS Approach to find the top view of a binary tree
static List<int> topView(Node root) {
var result = new List<int>();
if (root == null) return result;
// Horizontal distance -> (node's value, level)
var topNodes = new SortedDictionary<int, Tuple<int, int>>();
// Start DFS traversal
Dfs(root, 0, 0, topNodes);
// Collect nodes from the map
foreach (var value in topNodes.Values) {
result.Add(value.Item1);
}
return result;
}
static void Main(string[] args) {
// Create a sample binary tree
// 1
// / \
// 2 3
// / \ / \
// 4 5 6 7
Node root = new Node(1);
root.left = new Node(2);
root.right = new Node(3);
root.left.left = new Node(4);
root.left.right = new Node(5);
root.right.left = new Node(6);
root.right.right = new Node(7);
List<int> result = topView(root);
Console.WriteLine(string.Join(" ", result));
}
}
JavaScript
// JavaScript program to print
// top view of binary tree
// using dfs
class Node {
constructor(val) {
this.data = val;
this.left = null;
this.right = null;
}
}
function dfs(node, hd, level, topNodes) {
if (!node) return;
// If horizontal distance is encountered for
// the first time or if it's at a higher level
if (!(hd in topNodes) || topNodes[hd][1] > level) {
topNodes[hd] = [node.data, level];
}
// Recur for left and right subtrees
dfs(node.left, hd - 1, level + 1, topNodes);
dfs(node.right, hd + 1, level + 1, topNodes);
}
// DFS Approach to find the top view of a binary tree
function topView(root) {
let result = [];
if (!root) return result;
// Horizontal distance -> [node's value, level]
let topNodes = {};
// Start DFS traversal
dfs(root, 0, 0, topNodes);
// Collect nodes from the map
for (let key of Object.keys(topNodes).sort((a, b) => a - b)) {
result.push(topNodes[key][0]);
}
return result;
}
// driver code
// Create a sample binary tree
// 1
// / \
// 2 3
// / \ / \
// 4 5 6 7
const root = new Node(1);
root.left = new Node(2);
root.right = new Node(3);
root.left.left = new Node(4);
root.left.right = new Node(5);
root.right.left = new Node(6);
root.right.right = new Node(7);
const result = topView(root);
console.log(result.join(" "));
Using BFS - O(n * log n) Time and O(n) Space
The idea is similar to Vertical Order Traversal. Like vertical Order Traversal, we need to put nodes of the same horizontal distance together. We just do a level order traversal (bfs) instead of dfs so that the topmost node at a horizontal distance is visited before any other node of the same horizontal distance below it.
C++
// C++ program to print top
// view of binary tree
// using bfs
#include <bits/stdc++.h>
using namespace std;
class Node {
public:
int data;
Node* left;
Node* right;
Node(int val) {
data = val;
left = right = nullptr;
}
};
// Function to return the top view of a binary tree
vector<int> topView(Node *root) {
vector<int> result;
if (!root) return result;
// Map to store the first node at each
// horizontal distance (hd)
map<int, int> topNodes;
// Queue to store nodes along with their
// horizontal distance
queue<pair<Node*, int>> q;
// Start BFS with the root node at
// horizontal distance 0
q.push({root, 0});
while (!q.empty()) {
auto nodeHd = q.front();
// Current node
Node *node = nodeHd.first;
// Current horizontal distance
int hd = nodeHd.second;
q.pop();
// If this horizontal distance is seen for the first
// time, store the node
if (topNodes.find(hd) == topNodes.end()) {
topNodes[hd] = node->data;
}
// Add left child to the queue with horizontal
// distance - 1
if (node->left) {
q.push({node->left, hd - 1});
}
// Add right child to the queue with
// horizontal distance + 1
if (node->right) {
q.push({node->right, hd + 1});
}
}
// Extract the nodes from the map in sorted order
// of their horizontal distances
for (auto it : topNodes) {
result.push_back(it.second);
}
return result;
}
int main() {
// Create a sample binary tree
// 1
// / \
// 2 3
// / \ / \
// 4 5 6 7
Node* root = new Node(1);
root->left = new Node(2);
root->right = new Node(3);
root->left->left = new Node(4);
root->left->right = new Node(5);
root->right->left = new Node(6);
root->right->right = new Node(7);
vector<int> result = topView(root);
for (int i : result) {
cout << i << " ";
}
return 0;
}
Java
// Java program to print top
// view of binary tree
// using bfs
import java.util.*;
class Node {
int data;
Node left, right;
Node(int val) {
data = val;
left = right = null;
}
}
// Function to return the top view of a binary tree
class GfG {
static ArrayList<Integer> topView(Node root) {
ArrayList<Integer> result = new ArrayList<>();
if (root == null) return result;
// Map to store the first node at each
// horizontal distance (hd)
Map<Integer, Integer> topNodes = new TreeMap<>();
// Queue to store nodes along with their horizontal distance
Queue<Map.Entry<Node, Integer>> q = new LinkedList<>();
// Start BFS with the root node at horizontal distance 0
q.add(new AbstractMap.SimpleEntry<>(root, 0));
while (!q.isEmpty()) {
Map.Entry<Node, Integer> nodeHd = q.poll();
// Current node
Node node = nodeHd.getKey();
// Current horizontal distance
int hd = nodeHd.getValue();
// If this horizontal distance is seen for
// the first time, store the node
if (!topNodes.containsKey(hd)) {
topNodes.put(hd, node.data);
}
// Add left child to the queue with horizontal distance - 1
if (node.left != null) {
q.add(new AbstractMap.SimpleEntry<>(node.left, hd - 1));
}
// Add right child to the queue with horizontal
// distance + 1
if (node.right != null) {
q.add(new AbstractMap.SimpleEntry<>(node.right, hd + 1));
}
}
// Extract the nodes from the map in sorted order
// of their horizontal distances
for (Integer value : topNodes.values()) {
result.add(value);
}
return result;
}
public static void main(String[] args) {
// Create a sample binary tree
// 1
// / \
// 2 3
// / \ / \
// 4 5 6 7
Node root = new Node(1);
root.left = new Node(2);
root.right = new Node(3);
root.left.left = new Node(4);
root.left.right = new Node(5);
root.right.left = new Node(6);
root.right.right = new Node(7);
ArrayList<Integer> result = topView(root);
for (int i : result) {
System.out.print(i + " ");
}
}
}
Python
# Python program to print top
# view of binary tree
# using bfs
from collections import deque
class Node:
def __init__(self, val):
self.data = val
self.left = None
self.right = None
# Function to return the top view of
# a binary tree
def topView(root):
result = []
if not root:
return result
# Map to store the first node at each
# horizontal distance (hd)
topNodes = {}
# Queue to store nodes along with their horizontal distance
q = deque([(root, 0)])
# Start BFS with the root node at horizontal distance 0
while q:
node, hd = q.popleft()
# If this horizontal distance is seen for the
# first time, store the node
if hd not in topNodes:
topNodes[hd] = node.data
# Add left child to the queue with horizontal
# distance - 1
if node.left:
q.append((node.left, hd - 1))
# Add right child to the queue with horizontal
# distance + 1
if node.right:
q.append((node.right, hd + 1))
# Extract the nodes from the map in sorted order of
# their horizontal distances
for key in sorted(topNodes.keys()):
result.append(topNodes[key])
return result
if __name__ == "__main__":
# Create a sample binary tree
# 1
# / \
# 2 3
# / \ / \
# 4 5 6 7
root = Node(1)
root.left = Node(2)
root.right = Node(3)
root.left.left = Node(4)
root.left.right = Node(5)
root.right.left = Node(6)
root.right.right = Node(7)
result = topView(root)
print(" ".join(map(str, result)))
C#
// C# program to print top
// view of binary tree
// using bfs
using System;
using System.Collections.Generic;
class Node {
public int data;
public Node left, right;
public Node(int val) {
data = val;
left = right = null;
}
}
class GfG {
// Function to return the top view of a binary tree
static List<int> topView(Node root) {
List<int> result = new List<int>();
if (root == null)
return result;
// Map to store the first node at each horizontal
// distance (hd)
SortedDictionary<int, int> topNodes
= new SortedDictionary<int, int>();
// Queue to store nodes along with their horizontal
// distance
Queue<KeyValuePair<Node, int> > q
= new Queue<KeyValuePair<Node, int> >();
// Start BFS with the root node at horizontal
// distance 0
q.Enqueue(new KeyValuePair<Node, int>(root, 0));
while (q.Count > 0) {
var nodeHd = q.Dequeue();
// Current node
Node node = nodeHd.Key;
// Current horizontal distance
int hd = nodeHd.Value;
// If this horizontal distance is seen for the
// first time, store the node
if (!topNodes.ContainsKey(hd)) {
topNodes[hd] = node.data;
}
// Add left child to the queue with horizontal
// distance - 1
if (node.left != null) {
q.Enqueue(new KeyValuePair<Node, int>(
node.left, hd - 1));
}
// Add right child to the queue with horizontal
// distance + 1
if (node.right != null) {
q.Enqueue(new KeyValuePair<Node, int>(
node.right, hd + 1));
}
}
// Extract the nodes from the map in sorted order of
// their horizontal distances
foreach(var item in topNodes) {
result.Add(item.Value);
}
return result;
}
static void Main(string[] args) {
// Create a sample binary tree
// 1
// / \
// 2 3
// / \ / \
// 4 5 6 7
Node root = new Node(1);
root.left = new Node(2);
root.right = new Node(3);
root.left.left = new Node(4);
root.left.right = new Node(5);
root.right.left = new Node(6);
root.right.right = new Node(7);
List<int> result = topView(root);
foreach(int val in result) {
Console.Write(val + " ");
}
}
}
JavaScript
// JavaScript program to print top
// view of binary tree
// using bfs
class Node {
constructor(val) {
this.data = val;
this.left = null;
this.right = null;
}
}
// Function to return the top view of
// a binary tree
function topView(root) {
let result = [];
if (!root) return result;
// Map to store the first node at each
// horizontal distance (hd)
let topNodes = new Map();
// Queue to store nodes along with their
// horizontal distance
let q = [];
q.push([root, 0]);
// Start BFS with the root node at horizontal distance 0
while (q.length > 0) {
let [node, hd] = q.shift();
// If this horizontal distance is seen for the
// first time, store the node
if (!topNodes.has(hd)) {
topNodes.set(hd, node.data);
}
// Add left child to the queue with horizontal
// distance - 1
if (node.left) {
q.push([node.left, hd - 1]);
}
// Add right child to the queue with horizontal
// distance + 1
if (node.right) {
q.push([node.right, hd + 1]);
}
}
// Extract the nodes from the map in sorted order of their
// horizontal distances
for (let [key, value] of [...topNodes.entries()].sort((a, b) => a[0] - b[0])) {
result.push(value);
}
return result;
}
//driver code
// Create a sample binary tree
// 1
// / \
// 2 3
// / \ / \
// 4 5 6 7
let root = new Node(1);
root.left = new Node(2);
root.right = new Node(3);
root.left.left = new Node(4);
root.left.right = new Node(5);
root.right.left = new Node(6);
root.right.right = new Node(7);
let result = topView(root);
console.log(result.join(" "));
Optimized Approach Using BFS - O(n) Time and O(n) Space
A queue is used to perform level-order traversal, storing each node along with its corresponding horizontal distance from the root. hashmap keeps track of the topmost node at every horizontal distance. During traversal, if a node at a given horizontal distance is encountered for the first time, it is added to the map.
Additionally, the minimum horizontal distance (mn) is updated to organize the result. After completing the traversal, the map's values are transferred to a result array, adjusting indices based on mn to ensure the nodes are arranged correctly from leftmost to rightmost in the top view. BFS approach ensures that nodes closer to the root and encountered first are prioritized in the top view.
C++
// C++ program to print top view of binary tree
// optimally using bfs
#include <bits/stdc++.h>
using namespace std;
class Node {
public:
int data;
Node *left;
Node *right;
Node(int val) {
data = val;
left = right = nullptr;
}
};
// Function to return a list of nodes visible
// from the top view from left to right in Binary Tree.
vector<int> topView(Node *root) {
// base case
if (root == nullptr) {
return {};
}
Node *temp = nullptr;
// creating empty queue for level order traversal.
queue<pair<Node *, int>> q;
// creating a map to store nodes at a
// particular horizontal distance.
unordered_map<int, int> mp;
int mn = INT_MAX;
q.push({root, 0});
while (!q.empty()) {
temp = q.front().first;
int d = q.front().second;
mn = min(mn, d);
q.pop();
// storing temp->data in map.
if (mp.find(d) == mp.end()) {
mp[d] = temp->data;
}
// if left child of temp exists, pushing it in
// the queue with the horizontal distance.
if (temp->left) {
q.push({temp->left, d - 1});
}
// if right child of temp exists, pushing it in
// the queue with the horizontal distance.
if (temp->right) {
q.push({temp->right, d + 1});
}
}
vector<int> ans(mp.size());
// traversing the map and storing the nodes in list
// at every horizontal distance.
for (auto it = mp.begin(); it != mp.end(); it++) {
ans[it->first - mn] = (it->second);
}
return ans;
}
int main() {
// Create a sample binary tree
// 1
// / \
// 2 3
// / \ / \
// 4 5 6 7
Node *root = new Node(1);
root->left = new Node(2);
root->right = new Node(3);
root->left->left = new Node(4);
root->left->right = new Node(5);
root->right->left = new Node(6);
root->right->right = new Node(7);
vector<int> result = topView(root);
for (int i : result) {
cout << i << " ";
}
return 0;
}
Java
// Java program to print top view of binary tree
// optimally using bfs
import java.util.*;
class Node {
int data;
Node left, right;
Node(int val) {
data = val;
left = right = null;
}
}
class GfG {
// Function to return a list of nodes visible from the
// top view from left to right in Binary Tree.
static ArrayList<Integer> topView(Node root) {
// Base case: if the tree is empty, return an empty
// list
if (root == null) {
return new ArrayList<>();
}
// Queue to perform level order traversal.
// Each element in the queue is a pair of (Node,
// horizontal distance)
Queue<Pair> queue = new LinkedList<>();
queue.add(new Pair(root, 0));
// HashMap to store the first node at each
// horizontal distance
HashMap<Integer, Integer> map = new HashMap<>();
// Variables to track the minimum and maximum
// horizontal distances
int minHD = 0;
int maxHD = 0;
while (!queue.isEmpty()) {
Pair current = queue.poll();
Node currentNode = current.node;
int hd = current.dist;
// Update min and max horizontal distances
if (hd < minHD) {
minHD = hd;
}
if (hd > maxHD) {
maxHD = hd;
}
// If a horizontal distance is encountered for
// the first time, add it to the map
if (!map.containsKey(hd)) {
map.put(hd, currentNode.data);
}
// Enqueue the left child with horizontal
// distance hd - 1
if (currentNode.left != null) {
queue.add(
new Pair(currentNode.left, hd - 1));
}
// Enqueue the right child with horizontal
// distance hd + 1
if (currentNode.right != null) {
queue.add(
new Pair(currentNode.right, hd + 1));
}
}
// Prepare the result list by traversing from minHD
// to maxHD
ArrayList<Integer> topViewList = new ArrayList<>();
for (int hd = minHD; hd <= maxHD; hd++) {
if (map.containsKey(hd)) {
topViewList.add(map.get(hd));
}
}
return topViewList;
}
// Helper class to store a node along with its
// horizontal distance
static class Pair {
Node node;
int dist;
Pair(Node node, int dist) {
this.node = node;
this.dist = dist;
}
}
public static void main(String[] args) {
// Create a sample binary tree
// 1
// / \
// 2 3
// / \ / \
// 4 5 6 7
Node root = new Node(1);
root.left = new Node(2);
root.right = new Node(3);
root.left.left = new Node(4);
root.left.right = new Node(5);
root.right.left = new Node(6);
root.right.right = new Node(7);
ArrayList<Integer> result = topView(root);
for (int i : result) {
System.out.print(i + " ");
}
}
}
Python
# Python program to print top view of binary tree
# optimally using bfs
from queue import Queue
class Node:
def __init__(self, data):
self.data = data
self.left = None
self.right = None
# Function to return a list of nodes visible
# from the top view from left to right in Binary Tree.
def topView(root):
# base case
if not root:
return []
temp = None
# creating empty queue for level order traversal.
q = Queue()
# creating a dictionary to store nodes at a
# particular horizontal distance.
mp = {}
mn = float('inf')
q.put((root, 0))
while not q.empty():
temp, d = q.get()
mn = min(mn, d)
# storing temp.data in dictionary.
if d not in mp:
mp[d] = temp.data
# if left child of temp exists, pushing it in
# the queue with the horizontal distance.
if temp.left:
q.put((temp.left, d - 1))
# if right child of temp exists, pushing it in
# the queue with the horizontal distance.
if temp.right:
q.put((temp.right, d + 1))
# Initialize result array with size equal to dictionary size
ans = [0] * len(mp)
# Fill result array based on horizontal distances
for d, value in mp.items():
ans[d - mn] = value
return ans
if __name__ == "__main__":
# Create a sample binary tree
# 1
# / \
# 2 3
# / \ / \
# 4 5 6 7
root = Node(1)
root.left = Node(2)
root.right = Node(3)
root.left.left = Node(4)
root.left.right = Node(5)
root.right.left = Node(6)
root.right.right = Node(7)
result = topView(root)
print(" ".join(map(str, result)))
C#
// C# program to print top view of binary tree
// optimally using bfs
using System;
using System.Collections.Generic;
using System.Linq;
class Node {
public int data;
public Node left, right;
public Node(int val) {
data = val;
left = right = null;
}
}
class GfG {
// Function to return a list of nodes visible
// from the top view from left to right in Binary Tree.
public static List<int> TopView(Node root) {
// base case
if (root == null)
return new List<int>();
Node temp = null;
// creating empty queue for level order traversal.
Queue<(Node, int)> q = new Queue<(Node, int)>();
// creating a dictionary to store nodes at a
// particular horizontal distance.
Dictionary<int, int> mp
= new Dictionary<int, int>();
int mn = int.MaxValue;
q.Enqueue((root, 0));
while (q.Count > 0) {
var front = q.Dequeue();
temp = front.Item1;
int d = front.Item2;
mn = Math.Min(mn, d);
// storing temp.data in dictionary.
if (!mp.ContainsKey(d)) {
mp[d] = temp.data;
}
// if left child of temp exists, pushing it in
// the queue with the horizontal distance.
if (temp.left != null) {
q.Enqueue((temp.left, d - 1));
}
// if right child of temp exists, pushing it in
// the queue with the horizontal distance.
if (temp.right != null) {
q.Enqueue((temp.right, d + 1));
}
}
// Initialize result array with size equal to
// dictionary size
List<int> ans = new List<int>(new int[mp.Count]);
// Fill result array based on horizontal distances
foreach(var entry in mp) {
ans[entry.Key - mn] = entry.Value;
}
return ans;
}
static void Main(string[] args) {
// Create a sample binary tree
// 1
// / \
// 2 3
// / \ / \
// 4 5 6 7
Node root = new Node(1);
root.left = new Node(2);
root.right = new Node(3);
root.left.left = new Node(4);
root.left.right = new Node(5);
root.right.left = new Node(6);
root.right.right = new Node(7);
List<int> result = TopView(root);
Console.WriteLine(string.Join(" ", result));
}
}
JavaScript
// JavaScript program to print top view of binary tree
// optimally using bfs
class Node {
constructor(data) {
this.data = data;
this.left = null;
this.right = null;
}
}
function topView(root) {
// Base case
if (root === null) {
return [];
}
// Queue for level order traversal
let queue = [];
// Map to store nodes at a particular horizontal
// distance
let map = new Map();
// Track the minimum horizontal distance
let minDistance = Number.MAX_VALUE;
// Start with the root at horizontal distance 0
queue.push([ root, 0 ]);
while (queue.length > 0) {
let [temp, d] = queue.shift();
// Update the minimum horizontal distance
minDistance = Math.min(minDistance, d);
// If the horizontal distance is not yet in the map,
// add it
if (!map.has(d)) {
map.set(d, temp.data);
}
// Add left child with horizontal distance d - 1
if (temp.left) {
queue.push([ temp.left, d - 1 ]);
}
// Add right child with horizontal distance d + 1
if (temp.right) {
queue.push([ temp.right, d + 1 ]);
}
}
// Create the result array with size equal to map size
let ans = new Array(map.size);
// Populate the result array using the map
for (let [key, value] of map) {
ans[key - minDistance] = value;
}
return ans;
}
// Driver code
// Create a sample binary tree
// 1
// / \
// 2 3
// / \ / \
// 4 5 6 7
let root = new Node(1);
root.left = new Node(2);
root.right = new Node(3);
root.left.left = new Node(4);
root.left.right = new Node(5);
root.right.left = new Node(6);
root.right.right = new Node(7);
let result = topView(root);
console.log(result.join(" "));
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