For working professionals
For fresh graduates
More
A Comprehensive Guide on Softw…
1. Introduction
2. 2D Transformation In CSS
3. Informatica tutorial
4. Iterator Design Pattern
5. OpenCV Tutorial
6. PyTorch
7. Activity Diagram in UML
8. Activity selection problem
9. AI Tutorial
10. Airflow Tutorial
11. Android Studio
12. Android Tutorial
13. Animation CSS
14. Apache Kafka Tutorial
15. Apache Spark Tutorial
16. Apex Tutorial
17. App Tutorial
18. Appium Tutorial
19. Application Layer
20. Architecture of Data Warehouse
21. Armstrong Number
22. ASP Full Form
23. AutoCAD Tutorial
24. AWS Instance Types
25. Backend Technologies
26. Bash Scripting Tutorial
27. Belady's Anomaly
28. BGP Border Gateway Protocol
29. Binary Subtraction
30. Bipartite Graph
31. Bootstrap 5 tutorial
32. Box sizing in CSS
33. Bridge vs. Repeater
34. Builder Design Pattern
35. Button CSS
36. Change Font Color Using CSS
37. Circuit Switching and Packet Switching
38. Clustered and Non-clustered Index
39. Cobol Tutorial
40. CodeIgniter Tutorial
41. Compiler Design Tutorial
42. Complete Binary Trees
43. Components of IoT
44. Computer Network Tutorial
45. Convert Octal to Binary
46. CSS Border
47. CSS Colors
48. CSS Flexbox
49. CSS Float
50. CSS Font Properties
51. CSS Full Form
52. CSS Gradient
53. CSS Margin
54. CSS nth Child
55. CSS Syntax
56. CSS Tables
57. CSS Tricks
58. CSS Variables
59. Cucumber Tutorial
60. Cyclic Redundancy Check
61. Dart Tutorial
62. Data Structures and Algorithms (DSA)
63. DCL
64. Decision Tree Algorithm
65. DES Algorithm
66. Difference Between DDL and DML
67. Difference between Encapsulation and Abstraction
68. Difference Between GET and POST
69. Difference Between Hub and Switch
70. Difference Between IPv4 and IPv6
71. Difference Between Microprocessor And Microcontroller
72. Difference between PERT and CPM
73. Difference Between Primary Key and Foreign Key
74. Difference Between Process and Thread in Java
75. Difference between RAM and ROM
76. SRAM vs. DRAM: Understanding the Difference
77. Difference Between Structure and Union
78. Difference between TCP and UDP
79. Difference between Transport Layer and Network Layer
80. Disk Scheduling Algorithms
81. Display Property in CSS
82. Domain Name System
83. Dot Net Tutorial
84. ElasticSearch Tutorial
85. Entity Framework Tutorial
86. ES6 Tutorial
87. Factory Design Pattern in Java
88. File Transfer Protocol
89. Firebase Tutorial
90. First Come First Serve
91. Flutter Basics
92. Flutter Tutorial
93. Font Family in CSS
94. Go Language Tutorial
95. Golang Tutorial
96. Graphql Tutorial
97. Half Adder and Full Adder
98. Height of Binary Tree
99. Hibernate Tutorial
100. Hive Tutorial
101. How To Become A Data Scientist
102. How to Install Anaconda Navigator
103. Install Bootstrap
104. Google Colab - How to use Google Colab
105. Hypertext Transfer Protocol
106. Infix to Postfix Conversion
107. Install SASS
108. Internet Control Message Protocol (ICMP)
109. IPv 4 address
110. JCL Programming
111. JQ Tutorial
112. JSON Tutorial
113. JSP Tutorial
114. Junit Tutorial
115. Kadanes Algorithm
116. Kafka Tutorial
117. Knapsack Problem
118. Kth Smallest Element
119. Laravel Tutorial
120. Left view of binary tree
121. Level Order Traversal
122. Linear Gradient CSS
123. Link State Routing Algorithm
124. Longest Palindromic Subsequence
125. LRU Cache Implementation
126. Matrix Chain Multiplication
127. Maximum Product Subarray
128. Median of Two Sorted Arrays
129. Memory Hierarchy
130. Merge Two Sorted Arrays
131. Microservices Tutorial
132. Missing Number in Array
133. Mockito tutorial
134. Modem vs Router
135. Mulesoft Tutorial
136. Network Devices
137. Network Devices in Computer Networks
138. Next JS Tutorial
139. Nginx Tutorial
140. Object-Oriented Programming (OOP)
141. Octal to Decimal
142. OLAP Operations
143. Opacity CSS
144. OSI Model
145. CSS Overflow
146. Padding in CSS
147. Perimeter of A Rectangle
148. Perl scripting
149. Phases of Compiler
150. Placeholder CSS
151. Position Property in CSS
152. Postfix evaluation in C
153. Powershell Tutorial
154. Primary Key vs Unique Key
155. Program To Find Area Of Triangle
156. Pseudo-Classes in CSS
157. Pseudo elements in CSS
158. Pyspark Tutorial
159. Pythagorean Triplet in an Array
160. Python Tkinter Tutorial
161. Quality of Service
162. R Language Tutorial
163. R Programming Tutorial
164. RabbitMQ Tutorial
165. Redis Tutorial
166. Redux in React
167. Regex Tutorial
168. Relation Between Transport Layer And Network Layer
169. Array Rotation in Java
170. Routing Protocols
171. Ruby On Rails
172. Ruby tutorial
173. Scala Tutorial
174. Scatter Plot Matplotlib
175. Shadow CSS
176. Shell Scripting Tutorial
177. Singleton Design Pattern
178. Snowflake Tutorial
179. Socket Programming
180. Solidity Tutorial
181. SonarQube in Java
182. Spark Tutorial
183. Spiral Model In Software Engineering
184. Splunk Tutorial for Beginners
185. Structural Design Pattern
186. Subnetting in Computer Networks
187. Sum of N Natural Numbers
188. Swift Programming Tutorial
189. TCP 3 Way Handshake
190. TensorFlow Tutorial
191. Threaded Binary Tree
192. Top View Of Binary Tree
Now Reading
193. Transmission Control Protocol
194. Transport Layer Protocols
195. Traversal of Binary Tree
196. Types of Queue
197. TypeScript Tutorial
198. UDP Protocol
199. Ultrasonic Sensor Arduino Code
200. Unix Tutorial for Beginners
201. V Model in Software Engineering
202. Verilog Tutorial
203. Virtualization in Cloud Computing
204. Void Pointer
205. Vue JS Tutorial
206. Weak Entity Set
207. What is Bandwidth?
208. What is Big Data
209. Checksum
210. What is Design Pattern?
211. What is Ethernet
212. What is Link State Routing
213. What Is Port In Networking
214. What is ROM?
215. Page Fault in Operating Systems
216. WPF Tutorial
217. Wireshark Tutorial
218. XML Tutorial
We encounter different types of trees when working with data structures. Among them, binary trees are important. Now imagine standing on top of a tree and looking down. You would see the tree’s top. It is the concept of the top view of a binary tree in computer science.
A binary tree is a data structure in which each node can have a maximum of two children. These children are identified as the left and right children.
The top view is what you would see if you were to visualize a binary tree as a real tree and look down from above. As a result, you face the first node from each level from left to right.
Understanding this concept is important, as it forms the basis of many algorithms. It helps visualize how data is structured and stored in the tree.
Let's look closely at the 'top view of a binary tree'. This concept holds equal importance in many programming languages. Whether you are working with C++ or Java, understanding this concept is essential. For instance, knowing the top view of a binary tree in C++ and Java can help you develop efficient tree-based algorithms in these languages.
It is very important to keep practicing this concept to become an expert in coding. To help you master it, we will discuss in detail the top view of a binary tree example and discuss various methods to practice this concept.
A binary tree is a data structure type having a unique starting point called the root, from which two other items, known as child nodes, branch off.
Each of these child nodes can branch out into a maximum of two more nodes. This pattern continues and creates a structure that looks like a tree turned upside down - hence the name "tree".
Each node in the binary tree contains data. It has a pointer to the left child and another to the right child. When a node has no children, it's called a leaf node.
Top view of a binary tree example:
As we can see in this example, "1" is the root, and it has two children: "2" and "3". "2" and "3" are the parents of their respective children "4", "5", "6", and "7". "4", "5", "6", and "7" are leaf nodes because they don't have any children.
The top view of a binary tree provides a unique perspective on the tree's structure. It represents the nodes seen while looking at the tree from the very top. This view considers the nodes in each vertical line, or depth level, in the order of their appearance.
Consider an observer that can move left or right, but only downward, starting at the root node. As the observer travels and records the initial node at each depth level, they capture the top perspective of the tree once they have thoroughly investigated both the left and right sides.
In many branches of computer science, especially those working with data structures, understanding the top perspective is important. It facilitates a clearer understanding of the tree structure and is important for resolving many binary tree-related issues.
Whether you're working in Java, C++, or any other programming language, the theory remains the same, though the code implementation might differ.
To understand the top view of a binary tree, let's first visualize a real-world example. Picture yourself standing at the top of a tree and looking straight down. What do you see? You'll notice the highest branches and some lower ones that stick out to the side. This is similar to what we mean by the top view in a binary tree. The top view consists of the nodes that are observable when you observe the tree from its topmost point.
The top view of the above tree would include nodes
These are the first nodes visible from the top at each level, from left to right.
There is an attached diagram of the same binary tree but with only the nodes in the top view visible to make things clear.
This shows how data is structured.
Depth First Search (DFS), including inorder traversal, is a way to traverse or search tree or graph data structures. In Depth-First Search (DFS), the strategy is to travel as far down a single path as you can, and only when you hit the end do you trace back and start exploring the next path. It's like walking through a maze and always choosing the next path until you hit a dead-end, then returning to choose another path.
Inorder traversal is a specific type of Depth First Search (DFS) where you first visit the left subtree, then the root node, and finally the right subtree. When performed on a binary search tree, it visits the nodes in ascending order (from the smallest to the largest).
The inorder traversal of this binary tree would be 4, 2, 5, 1, 6, 3, 7.
This algorithm represents the classes and relationships involved in creating a binary tree and performing a DFS with inorder traversal.
We have two classes here: TreeNode and BinaryTree.
TreeNode Class:
The TreeNode class represents a single node in a binary tree. Each node has three attributes:
The TreeNode class also has a constructor method, TreeNode(int data), which is used to create a new node with a given data value.
BinaryTree Class:
The BinaryTree class represents the whole binary tree. It has two attributes:
The BinaryTree class also has two methods:
Relationships-
Each TreeNode instance has relationships with up to two other TreeNode instances (its children). It's depicted in the diagram with the "1 *.. '0..2'" line, showing each TreeNode can have 0 to 2 children.
The BinaryTree instance has a relationship with one TreeNode instance - its root. This relationship is depicted as "1 *-- '0..1'", showing that the BinaryTree has exactly one root.
Breadth First Search (BFS), also known as Level Order Traversal, is another method for exploring a tree or graph data structure. Unlike Depth First Search (DFS), BFS explores all the nodes at the current depth, or 'level', before moving on to nodes at the next depth level.
In a BFS, or Level Order traversal, on a binary tree, we start at the root, then visit all nodes at depth 1, followed by all nodes at depth 2, and so on.
If we apply the Level Order Traversal technique to this binary tree, the output would be 1, 2, 3, 4, 5, 6, 7.
Here's how it works:
BFS or Level Order Traversal can be useful when you want to find the shortest path in a tree or graph or when you want to visit nodes in order of their depth. It's a fundamental method in many algorithms involving trees or graphs.
In C++, we implement the top view of a binary tree by combining a level order traversal (Breadth-First Search) with a technique that tracks the horizontal distance of each node from the root.
We first define the node structure in C++. It includes the data value and pointers to the left and right child nodes.
Code-
struct Node {
int data;
Node* left;
Node* right;
};
Next, we create a function to create new nodes easily.
Code-
Node* makeNode(int data) {
Node* node = new Node();
if (!node) {
cout << "Memory error\n";
return NULL;
}
node->data = data;
node->left = node->right = NULL;
return node;
}
Finally, we implement the function to print the top view. We use a queue for the level order traversal and a map to store nodes along with their horizontal distances.
Code-
void topView(struct Node* root) {
if (root == NULL) return;
queue<pair<Node*, int>> q;
map<int, int> m;
q.push({ root, 0 });
while (!q.empty()) {
Node* temp = q.front().first;
int h = q.front().second;
q.pop();
if (!m[h]) m[h] = temp->data;
if (temp->left) q.push({ temp->left, h - 1 });
if (temp->right) q.push({ temp->right, h + 1 });
}
for (auto i = m.begin(); i != m.end(); i++) {
cout << i->second << " ";
}
}
A simple explanation of the given code:
Test the Code with a Binary Tree-
Now we can test our code with a binary tree.
Code-
int main() {
Node* root = makeNode(1);
root->left = makeNode(2);
root->right = makeNode(3);
root->left->left = makeNode(4);
root->left->right = makeNode(5);
root->right->left = makeNode(6);
root->right->right = makeNode(7);
cout << "Top view of the given binary tree is: ";
topView(root);
return 0;
}
When you run the program, the output will be:
In the case of Java, we'll be using a TreeMap to keep track of each node's horizontal distance and a Queue to perform a level order traversal.
Firstly, we'll define a “Node” class:
Code-
class Node {
int data;
Node left, right;
public Node(int item) {
data = item;
left = right = null;
}
}
Next, we'll create a BinaryTree class and implement the function to print the top view:
Code-
import java.util.*;
class BinaryTree {
Node root;
class QueueObj {
Node node;
int hd;
QueueObj(Node node, int hd) {
this.node = node;
this.hd = hd;
}
}
public void topView(Node root) {
if (root == null) return;
Queue<QueueObj> queue = new LinkedList<>();
Map<Integer, Node> topViewMap = new TreeMap<>();
queue.add(new QueueObj(root, 0));
while (!queue.isEmpty()) {
QueueObj tmpNode = queue.poll();
if (!topViewMap.containsKey(tmpNode.hd)) {
topViewMap.put(tmpNode.hd, tmpNode.node);
}
if (tmpNode.node.left != null) {
queue.add(new QueueObj(tmpNode.node.left, tmpNode.hd - 1));
}
if (tmpNode.node.right != null) {
queue.add(new QueueObj(tmpNode.node.right, tmpNode.hd + 1));
}
}
for (Map.Entry<Integer, Node> entry : topViewMap.entrySet()) {
System.out.print(entry.getValue().data + " ");
}
}
}
A simple explanation of the above codes:
Now, let's test the above code with a binary tree
Code-
public class Main {
public static void main(String[] args) {
BinaryTree tree = new BinaryTree();
tree.root = new Node(1);
tree.root.left = new Node(2);
tree.root.right = new Node(3);
tree.root.left.left = new Node(4);
tree.root.left.right = new Node(5);
tree.root.right.left = new Node(6);
tree.root.right.right = new Node(7);
System.out.println("Top view of the given binary tree is: ");
tree.topView(tree.root);
}
}
Output-
Understanding the top view of a binary tree is vital for mastering tree data structures. With the practical examples and step-by-step instructions provided, you should now have a good grasp of how to implement it in C++ and Java. To solidify your understanding, consider undertaking some top view of binary tree practice. These will further equip you with the skills needed to tackle more complex problems involving binary trees.
Binary trees, especially balanced ones, allow faster search, insertion, and deletion operations than linked lists.
The height is the longest path from the root node to the leaf node.
In a BST, nodes on the left are always less than the root, and nodes on the right are always greater.
Balanced binary trees ensure operations like search, insert, and delete run in logarithmic time, preventing worst-case scenarios.
Author
Talk to our experts. We are available 7 days a week, 9 AM to 12 AM (midnight)
Indian Nationals
1800 210 2020
Foreign Nationals
+918045604032
1.The above statistics depend on various factors and individual results may vary. Past performance is no guarantee of future results.
2.The student assumes full responsibility for all expenses associated with visas, travel, & related costs. upGrad does not provide any a.