Computer Science & Engineering Computer Science & Engineering
Computer Science & Engineering Computer Science & Engineering
Experiment 2.2
struct TreeNode {
int val;
TreeNode* left;
TreeNode* right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
DEPARTMENT OF
COMPUTER SCIENCE & ENGINEERING
q.push(make_pair(root, 0));
while (!q.empty()) {
TreeNode* node = q.front().first;
int hd = q.front().second;
q.pop();
if (topViewMap.find(hd) == topViewMap.end()) {
topViewMap[hd] = node->val;
}
if (node->left) {
q.push(make_pair(node->left, hd - 1));
}
if (node->right) {
q.push(make_pair(node->right, hd + 1));
}
}
DEPARTMENT OF
COMPUTER SCIENCE & ENGINEERING
int main() {
topView(root);
return 0;
}
Result:
DEPARTMENT OF
COMPUTER SCIENCE & ENGINEERING
b) #include <bits/stdc++.h>
using namespace std;
class Node {
public:
int data;
Node* left;
Node* right;
class Tree {
public:
Node* create_Node(int data) {
return new Node(data);
}
DEPARTMENT OF
COMPUTER SCIENCE & ENGINEERING
int main() {
vector<int> numbers;
int number;
while (cin >> number) {
numbers.push_back(number);
}
Tree tree;
Node* root = tree.create_Node(numbers[0]);
for (size_t i = 1; i < numbers.size(); i++) {
tree.insert(root, numbers[i]);
DEPARTMENT OF
COMPUTER SCIENCE & ENGINEERING
tree.inorder_Traversal(root);
return 0;
}
Result:
Learning Outcome
• Learned about trees
• Tree is a fundamental data structure that resembles an upside-
down tree with a single root and branches of child nodes
spreading out from that root.
• Graphs are used to represent relationships and connections
between various objects, and they are a fundamental concept
in various algorithms and applications.