Skip to content

Instantly share code, notes, and snippets.

@graphoarty
Created November 28, 2020 04:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save graphoarty/c4eb63c74f5e9c8120152218e1f21cf1 to your computer and use it in GitHub Desktop.
Save graphoarty/c4eb63c74f5e9c8120152218e1f21cf1 to your computer and use it in GitHub Desktop.
Tree - Top View in C++
#include<bits/stdc++.h>
using namespace std;
class Node {
public:
int data;
Node *left;
Node *right;
Node(int d) {
data = d;
left = NULL;
right = NULL;
}
};
class Solution {
public:
Node* insert(Node* root, int data) {
if(root == NULL) {
return new Node(data);
} else {
Node* cur;
if(data <= root->data) {
cur = insert(root->left, data);
root->left = cur;
} else {
cur = insert(root->right, data);
root->right = cur;
}
return root;
}
}
/*
class Node {
public:
int data;
Node *left;
Node *right;
Node(int d) {
data = d;
left = NULL;
right = NULL;
}
};
*/
vector<int> costValues;
vector<int> dataValues;
vector<int> levelValues;
void print_vector(vector<int> arr){
for(int i = 0; i < (int) arr.size(); i++){
cout << arr[i] << " ";
}
cout << "\n";
}
void inOrder(Node* root, int cost, int level){
if(root->left != NULL){
inOrder(root->left, cost - 1, level + 1);
}
dataValues.push_back(root->data);
costValues.push_back(cost);
levelValues.push_back(level);
if(root->right != NULL){
inOrder(root->right, cost + 1, level + 1);
}
}
void topView(Node* root) {
inOrder(root, 0, 0);
for (int i = 0; i < (int) costValues.size() -1; i++){
for (int j = 0; j < (int) costValues.size() - i - 1; j++){
if (costValues[j] > costValues[j+1]){
int temp = costValues[j];
costValues[j] = costValues[j + 1];
costValues[j + 1] = temp;
temp = levelValues[j];
levelValues[j] = levelValues[j + 1];
levelValues[j + 1] = temp;
temp = dataValues[j];
dataValues[j] = dataValues[j + 1];
dataValues[j + 1] = temp;
}
}
}
vector<int> visitedValues;
vector<int> finalDataValues;
for(int i = 0; i < (int) costValues.size(); i++){
int current_cost = costValues[i];
int minLevel = 999999;
int dataValue = 0;
while(costValues[i] == current_cost){
if(levelValues[i] < minLevel){
minLevel = levelValues[i];
dataValue = dataValues[i];
}
i++;
}
cout << dataValue << " ";
i--;
}
}
}; //End of Solution
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment