diff --git a/C++/tree-top-view.cpp b/C++/tree-top-view.cpp new file mode 100644 index 0000000..a6635a6 --- /dev/null +++ b/C++/tree-top-view.cpp @@ -0,0 +1,98 @@ +#include +using namespace std; + +class node{ + public: + int data; + node* left; + node* right; + + node(int d){ + data = d; + left = right = NULL; + } +}; + +node* create(int ino[], int pre[], int s, int e){ + static int i=0; + if(s>e) + return NULL; + + node* root = new node(pre[i]); + int index =1; + for(int j=s;j<=e;j++) + { + if(ino[j]==pre[i]) + { + index = j; + break; + } + } + i++; + root->left = create(ino,pre,s,index-1); + root->right = create(ino,pre,index+1,e); + return root; +} + +void insert(node* &root, int key) +{ + queue q; + + if(root==NULL) + { + root = new node(key); + return; + } + q.push(root); + while (!q.empty()) { + node* root = q.front(); + q.pop(); + + if (!root->left) { + if(key!=-1) + root->left = new node(key); + else + root->left = NULL; + break; + } else + q.push(root->left); + + if (!root->right) { + if(key!=-1) + root->right = new node(key); + else + root->right = NULL; + break; + } else + q.push(root->right); + } +} + +void printtop(node* root){ + if(root==NULL) + return; + + printtop(root->left); + cout<data<<" "; +} + +void printtop2(node* root){ + if(root==NULL) + return; + cout<data<<" "; + printtop(root->right); + +} + +int main(){ + int d; + + node* root = NULL; + while(scanf("%d",&d)!=EOF) + { + insert(root,d); + } + + printtop(root); + printtop2(root->right); +} diff --git a/README.md b/README.md index 4fa2dc2..f0bb5dd 100644 --- a/README.md +++ b/README.md @@ -54,8 +54,10 @@ This repository is a collection of various algorithms & data structures covering - [Tower Of Hanoi](C++/tower-of-hanoi.cpp) - [Tree BFS](C++/tree-bfs.cpp) - [Tree DFS](C++/tree-dfs.cpp) +- [Tree Top View](C++/tree-top-view.cpp) - [Triplets](C++/triplets.cpp) - [Euclid Extended](C++/euclid-extended.cpp) + ### HTML - [Digital Clock](HTML/digital-clock.html)